Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminal: CURL | walk to JsonPath | prettyprint JSON

Tags:

json

shell

I am looking for a possibility to print parts of a returned JSON document on the shell.

Right now, I am piping a HTTP response from cURL to python to prettyprint it:

curl -vX GET http://foo.bar | python -mjson.tool

But now I would like to know how I could actually "walk" the path to a subarray?

If was for example the returned JSON data:

{
"value1": true,
"value2": {
            "subvalue1": "foo",
            "subvalue2": "bar"
          }
}

How could I only print the subarray in this example?

like image 426
chris polzer Avatar asked Apr 17 '11 13:04

chris polzer


People also ask

How do I get JSON with Curl?

To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.

How do you beautify Curl output?

In cURL requests, the default JSON output is in compact format. In cURL, we can use or pipe the json_pp to pretty print the JSON output.


1 Answers

Terry Jones wrote a nice tool for doing exactly this a few months ago. Here's his blog post about it http://blogs.fluidinfo.com/terry/2010/11/25/jsongrep-py-python-for-extracting-pieces-of-json-objects/.

Basically, for your example you would run

curl -vX GET http://foo.bar | jsongrep.py value2

By the way, I don't think your example is actually valid JSON. The subarray (actually a sub-object in JSON terms) should just be

{
   "subvalue1": "foo",
   "subvalue2": "bar"
}
like image 57
Eric Seidel Avatar answered Nov 15 '22 00:11

Eric Seidel