I am getting Json output(Missing quotes in jsonString) from my 3rd party API I wan to parse the output and get one of the property value.
Below are the sample code:
echo "Hello World!"
testValue='[{name: bhanu,dept:test}]'
echo " test value " $testValue
echo "$testValue" | jq -r '.[0].name
Getting below error:
parse error: Invalid literal at line 1, column 8
Can you please help me on it.
CodePudding user response:
here it is the correct syntax:
echo '[{"name": "bhanu","dept":"test"}]' | jq -r '.[0].name'
bhanu
in your case(json not stringified) you can use a little help from sed:
echo '[{name: bhanu,dept:test}]' | sed 's/[a-zA-Z]\ /"&"/g' | jq -r '.[0].name'
bhanu
CodePudding user response:
As pointed out by @R2D2, if you wish to use jq, one option would be to modify the value of testValue so that it is valid JSON, e.g. manually or using some text-wrangling tools.
There are potentially two other options you might wish to consider:
- change whatever it is that is producing the JSON-like text so that it produces JSON or some JSON variant for which a converter to JSON exists
- modify the value of testValue so that it is valid as a jq program, e.g.
testValue='[{name: "bhanu", dept: "test"}]'
jq -rn "$testValue | .[0].name"