Parsing JSON in Shell scripts

This can be simple by using jq.

This is a command line JSON processor. Here are a couple of examples of what can be done:

$ cat json.txt

{
        "name": "Google",
        "location":
                {
                        "street": "1600 Amphitheatre Parkway",
                        "city": "Mountain View",
                        "state": "California",
                        "country": "US"
                },
        "employees":
                [
                        {
                                "name": "Michael",
                                "division": "Engineering"
                        },
                        {
                                "name": "Laura",
                                "division": "HR"
                        },
                        {
                                "name": "Elise",
                                "division": "Marketing"
                        }
                ]
}

To parse a JSON object:

jq '.name' < json.txt

"Google"

To parse a nested JSON object:

$ jq '.location.city' < json.txt

"Mountain View"

To parse a JSON array:

$ jq '.employees[0].name' < json.txt

"Michael"

To extract specific fields from a JSON object:

$ jq '.location | {street, city}' < json.txt

{
  "city": "Mountain View",
  "street": "1600 Amphitheatre Parkway"
}