Reputation: 59
I am working on an assignment about parsing JSON by shell script. Is there any way that I can get the values from the JSON when executing it? For example, I'like to output id, body, and age's value. I am trying to use cut, sed, grep, but not jq. Should I use for-loop? Currently, I only can redirect the json to a txt file.
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "[email protected]",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora",
"age": 28
}
Upvotes: 2
Views: 837
Reputation: 72746
If you really must use the shell approach (which has many pitfalls, really) AND your actual json input is not very different from what you have shown, this is my take. Read two fields, the key and value, and if the key matches, do something with the value.
while read -r key value; do
case $key in
('"id":') printf '%s\n' "id=${value%,}";;
('"body":') printf '%s\n' "body=${value%,}";;
esac
done < json.txt
This will output
id=1
body="laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora"
Upvotes: 2