简体   繁体   中英

Shell Script - get values from JSON

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": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora",
"age": 28
}

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM