0

I am new to shell scripting,
I want to read a json variable's attribute values,
I have a sample json like -

{
    "userId": 1,
    "name": "jhonny",
    "cities": [{
        "id": 1,
        "name": "KL"
    }],
    "otherinfo": {
        "hobby": "reading",
        "nickname": "john"
    }
}

I tried the following script -

#!/bin/bash

temp='{"userId":1,"name":"jhonny","cities":[{"id":1,"name":"KL"}],"otherinfo":{"hobby":"reading","nickname":"john"}}'

echo $temp | jq .name

I get a test.sh: line 4: jq: command not found I am following this -
Read JSON variable in Shell Script

Can someone help how I could extract cities[0].name and otherinfo.nickname from the shell variable?

11
  • 3
    Did you install jq? stedolan.github.io/jq Commented Nov 5, 2019 at 16:32
  • Is it possible with any installation? I just tried that answer but didn’t know it required installation Commented Nov 5, 2019 at 16:34
  • I don't know. Can you please check the website? I learned today that this is sed for JSON data basically, but is not a standard tool of course which will be pre-installed with your OS. Commented Nov 5, 2019 at 16:39
  • 2
    If you're working with json, you need a tool that understands the format, like jq. Commented Nov 5, 2019 at 16:54
  • 1
    @stephanmg, ...please don't encourage folks -- reinventions of that wheel pretty much always end up getting the corner cases wrong, thus resulting in brittle systems that fail whenever data changes in unanticipated ways. The canonical response to folks trying to do regex-based "parsing" of HTML comes to mind. Commented Nov 5, 2019 at 21:49

1 Answer 1

0

The JSON module is a standard part of Python3, so if you don't want to install jq, you could maybe use Python:

python3 -c 'import json,sys;JSON=json.load(sys.stdin);print(JSON["cities"][0]["name"]);print(JSON["otherinfo"]["nickname"]);' < data.json

Sample Output

KL
john

That assumes your JSON data is in a file called data.json. If it's in a shell variable called JSON, omit the < data.json from the end and use:

echo "$JSON" | python3 -c ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.