2

I am trying to loads and print JSON response in shell script.I dont have any idea how to achieve this.Please help me on this.

Code:

#!/bin/sh

malop_q=$(curl -X GET -k -H "SEC: xxxxxxxxxxxxxxxxxxxxxx" 'https://127.0.0.1/api/reference_data/sets/malopid?fields=data(value)')

echo $malop_q

JSON Response:

{"data":[{"value":"11.945403842773683082"},{"value":"11.945403842773683082"},{"value":"11.945403842773683082"}]}

Expected OP is

I need to print values from above JSON response is:

11.945403842773683082
11.945403842773683082
11.945403842773683082

Thanks in advance.

'

3
  • Are you looking for "bash only" answer? or answer which uses python? Commented May 31, 2016 at 7:55
  • 3
    Have a look at jq. Using text processing tools (like awk) for parsing json is never the best idea. Use a tool that has json parsing libraries. Commented May 31, 2016 at 8:03
  • Yes, I required bash only Commented May 31, 2016 at 9:02

2 Answers 2

2

The following python code do the parsing, assuming that you save it as: my_json.py

import json,sys

obj=json.load(sys.stdin)
for i in range(len(obj['data'])):
    print obj['data'][i]['value']

You can get the respond using:

malop_q=$(curl -X GET -k -H "SEC: xxxxxxxxxxxxxxxxxxxxxx" 'https://127.0.0.1/api/reference_data/sets/malopid?fields=data(value)')   
echo $malop_q | python my_json.py

or in one line:

curl -X GET -k -H "SEC: xxxxxxxxxxxxxxxxxxxxxx" 'https://127.0.0.1/api/reference_data/sets/malopid?fields=data(value)' | python my_json.py
Sign up to request clarification or add additional context in comments.

Comments

2

With Python :

import json

with open('file.json') as json_file:    
    datas = json.load(json_file)

for d in datas["data"]:
  print(d["value"])

Comments

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.