Reputation: 19
I have a bash script (running on git bash for windows) that uses curl to get a json response from a server. The response contain a field that contain json data. The response looks like this:
[{
"Status": "A",
"JSON": "{\"field1\":\"value1\"}"
}, {
"Status": "B",
"JSON": "{\"field1\":\"value2\"}"
}]
here is the bash script I am trying to parse this string with:
#!/bin/bash
echo "parsing result in variable"
result='[{"Status":"A", "JSON":"{\"field1\":\"value1\"}"},{"Status":"B", "JSON":"{\"field1\":\"value2\"}"}]'
echo $result > json_in_json.json
result=$(echo "$result" | jq '[.[]."Status"]')
echo $result
echo "parsing result from file"
jq '[.[]."Status"]' json_in_json.json
and here is what I see in terminal
parsing result in variable
[{"Status":"A", "JSON":"{\"field1\":\"value1\"}"},{"Status":"B", "JSON":"{\"field1\":\"value2\"}"}]
]B",
parsing result from file
[
"A",
"B"
]
Is there a way to make jq output the same result without going through a temp file?
Upvotes: 0
Views: 592
Reputation: 19
I had filed a bug with jq about this, but closed it since it wasn't reproducible on ubuntu or macos. Nico Williams explained what is happening here:
https://github.com/stedolan/jq/issues/1855
Upvotes: 0
Reputation: 531693
jq
provides a fromjson
function to parse embedded JSON. For example,
$ jq '.[].JSON | fromjson | .field1' tmp.json
"value1"
"value2"
Update:
The problem is not jq
, but the fact that tee
writes its input to standard output as well as to any files named as arguments. Redirect to /dev/null
echo "$result" | tee json_in_json.json > /dev/null
or don't use tee
in the first place.
echo "$result" > json_in_json.json
Upvotes: 1