1

My json file has the below content:

{
  "Fruits": {
    "counter": 1,
    "protocols": [
      {
        "id": "100",
        "name": "lemon",
        "category": "citrus"
      },
      {
        "id": "350",
        "name": "Orange",
        "category": "citrus"
      },
      {
        "id": "150",
        "name": "lime",
        "category": "citrus"
      }
    ]
  }
}

I am expecting an output as below

Fruits:lemon:citrus
Fruits:Orange:citrus
Fruits:lime:citrus
1
  • 4
    Don't use grep to process JSON. Use jq Commented May 8, 2020 at 23:49

2 Answers 2

5

Easy to do with jq:

$ jq -r '.Fruits.protocols[] | "Fruits:\(.name):\(.category)"' input.json
Fruits:lemon:citrus
Fruits:Orange:citrus
Fruits:lime:citrus
Sign up to request clarification or add additional context in comments.

5 Comments

Nice!, I really like jq it becomes easy to parse json files using the shell.
Thank you. Unfortunately jq cannot be installed in my production environment. Is there any other alternative?
@apoonkun What a pity, as the solution is very nice. If you have Ruby, you can try my answer. Maybe it helps you.
@apoonkun You could use perl or python also, but, really, trying to do shell scripting that manipulates JSON without using jq is a Bad Idea.
Even in git-bash you can install jq :-)
0

The jq answer is better. Still posting a Ruby solution (if you cannot use jq), but it is less elegant:

ruby -e '
  require "json";
  l="";
  ARGF.each { |x| l+=x };
  obj=JSON.parse(l);
  obj["Fruits"]["protocols"].each { |x| puts "Fruits:#{x["name"]}:#{x["category"]}" }
'

Here is the full example:

echo '{"Fruits":{"counter":1,"protocols":[{"id":"100","name":"lemon","category":"citrus"},{"id":"350","name":"Orange","category":"citrus" },{"id":"150","name":"lime","category":"citrus"}]}}' \
| ruby -e 'require "json";l="";ARGF.each { |x| l+=x } ; obj=JSON.parse(l) ; obj["Fruits"]["protocols"].each { |x| puts "Fruits:#{x["name"]}:#{x["category"]}" }'

Output:

Fruits:lemon:citrus
Fruits:Orange:citrus
Fruits:lime:citrus

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.