0

How can I fetch the value of a key-value pair in a JSON using shell script I do not know the positions of key-value pairs in the JSON, I will have to search and get the value of the key-value pair.

{
    "firstName": "Rajesh",
    "lastName": "Kumar",
    "gender": "man",
    "age": 24,
    "address": {
        "streetAddress": "126 Udhna",
        "city": "Surat",
        "state": "GJ",
        "postalCode": "394221",
        "state": "WB"
    },
    "phoneNumbers": [
        { "type": "home", "number": "7383627627" }
    ]
}

Sample JSON. I will have to fetch the value of the city and I do not know the position of it as I will have to search and fetch the value.

Holger Just
  • 52,918
  • 14
  • 115
  • 123

2 Answers2

2

JSON objects do not have a position (well, they have in the written-out file but another order would be considered equal). Arrays do have an order.

The city field is located within the address field of the outermost object. Therefore, using jq, you can access it with the filter .address.city. The -r option unwraps the resulting JSON string into a raw string for the output.

jq -r '.address.city' input.json
Surat

Demo

pmf
  • 24,478
  • 2
  • 22
  • 31
0

You could get all occurrences of the values corresponding to a key named "city" by:

jq '..|objects|.city  // empty'
peak
  • 105,803
  • 17
  • 152
  • 177