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?
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.
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With