SRIRAM RAMACHANDRAN
SRIRAM RAMACHANDRAN

Reputation: 337

How to create array from json data in shell script

I used to read the json file using

recordtype=python -c 'import sys,json,ast;print ast.literal_eval(json.dumps(json.load(sys.stdin)["record"].keys())) < 1.json

I got the value of recordtype like

['1', '2', '3', '4']

In order for me to loop to the recordtype, I need the array like this

(1 2 3 4)

How to convert the above to this type of array? And if its possible to loop through the above value? I used

for type in "${recordtype[@]}"

The json would be:

{"modes":["a","b","c"],"recordtype":{"1":{"mode":"a","inputpath":"/us/","archive":""},"2":{"mode":"b","inputpath":"","archive":""}}}

Upvotes: 1

Views: 472

Answers (1)

iBug
iBug

Reputation: 37287

What about running though the generated string again?

arr=($(echo "['1', '2', '3', '4']" | grep -oP "'[^']*'" | awk '{print substr($0, 2, length($0) - 2)}'))

This extracts everything between single quotes, then strips the quotes on the sides, and gives what you want.

ibug@linux:~ $ echo "${arr[@]}"
1 2 3 4
ibug@linux:~ $ for i in "${arr[@]}"; do echo "$i"; done
1
2
3
4
ibug@linux:~ $

Upvotes: 1

Related Questions