2

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
}
8
  • 3
    jq is the right tool for the job. Why aren't you using it? Commented Jun 16, 2020 at 3:08
  • The assignment requires not using jq, only sed, grep, etc. Commented Jun 16, 2020 at 3:27
  • You should show your best effort so far. That will guide those who might help. Does the JSON input consist of a single object as shown in the question, or could there be multiple objects? When you say "output ID, body and age", what form should that output take? Commented Jun 16, 2020 at 3:58
  • 1
    sed and grep are both regular-expression-based, and therefore not capable of parsing things like JSON that can contain nested syntax (e.g. JSON allows arrays within arrays within arrays within....). It's in the same category as HTML. You can fake it if the JSON is simple enough, but parsing JSON with regex will fail if the JSON isn't in the exact format you expect. Commented Jun 16, 2020 at 4:34
  • @ Gordon, If I understand you correctly, sed and grep can not doing like remove the bracket, comma, and the keys. Then only leaves those values? Commented Jun 16, 2020 at 7:15

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

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.