1

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":""}}}
3
  • Could we get the file 1.json type sample data, please. Commented Jan 30, 2018 at 13:38
  • { "modes": [ "a", "b", "c" ], "recordtype": { "1": { "mode":"a", "inputpath":"/us/", "archive":"" }, "2": { "mode":"b", "inputpath":"", "archive":"" } } } Commented Jan 30, 2018 at 14:53
  • Please, add it to the original post. Commented Jan 30, 2018 at 15:03

1 Answer 1

1

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:~ $
Sign up to request clarification or add additional context in comments.

5 Comments

yeah thanks its working. But the issue it can't be static. The array is dynamic. And can you explain me the print part after awk?
@SRIRAMRAMACHANDRAN The array is dynamic. Just replace the first part echo "[...]" with your actual output.
@SRIRAMRAMACHANDRAN The print part is an AWK program that removes the first and the last character from each line, which is the unwanted single quotes.
thanks for the explanation... and what does substr doing?
@SRIRAMRAMACHANDRAN It's the core part that does the quote-stripping job. It takes the substring starting from position 2, with a length of length - 2, which should be the part of the string exactly without the quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.