Get your server issues fixed by our experts for a price starting at just 25 USD/Hour. Click here to register and open a ticket with us now!

Author Topic: How to parse JSON string via command line on Linux  (Read 1257 times)

0 Members and 1 Guest are viewing this topic.

Amal John Ronkha

  • Newbie
  • *
  • Posts: 6
  • Karma: +0/-0
How to parse JSON string via command line on Linux
« on: July 14, 2018, 12:54:55 pm »
A command-line JSON parser can be handy when you test or debug JSON web services. You can feed JSON-formatted responses from web services into the command-line JSON parser, thereby easily inspecting otherwise hard-to-read JSON responses or extracting individual objects from them.

How to parse JSON string from the command line?

On Linux, there is a command-line JSON processor called jq which does exactly that. Using jq, you can parse, filter, map, and transform JSON-structured data effortlessly.

To install jq on Linux, simply download its binary (available for 32-bit and 64-bit system separately) as follows.

Code: [Select]
$ wget http://stedolan.github.io/jq/download/linux32/jq (32-bit system)
$ wget http://stedolan.github.io/jq/download/linux64/jq (64-bit system)
$ chmod +x ./jq
$ sudo cp jq /usr/bin

The following examples illustrate how to parse JSON-structured data with jq.

An example JSON Schema:

Code: [Select]
$ cat json.txt
Code: [Select]
{
        "server": "US-Cloud",
        "location":
                {
                        "street": "1600 Amphitheatre Parkway",
                        "city": "Mountain View",
                        "state": "California",
                        "country": "US"
                },
        "support":
                [
                        {
                                "name": "James",
                                "division": "Call Support"
                        },
                        {
                                "name": "Peter",
                                "division": "Mail Support"
                        },
                        {
                                "name": "Alice",
                                "division": "Live Support"
                        }
                ]
}

To parse a JSON object:

Code: [Select]
$ cat json.txt | jq '.server'

US-Cloud

To parse a nested JSON object:
Code: [Select]
$ cat json.txt | jq '.location.city'

"Mountain View"

To parse a JSON array:

Code: [Select]
$ cat json.txt | jq '.employees[0].name'

"Michael"

To extract specific fields from a JSON object:

Code: [Select]
$ cat json.txt | jq '.location | {street, city}'

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

Hope this helps! :)