Technical Musings: Python JSON one-liner

Thursday, January 12, 2012

Python JSON one-liner

I've seen the python one-liner to parse and pretty-print json:

cat test.json | python -mjson.tool

But I still have to grep/awk to get the value.  Here's a python one-liner to get a json value:

curl -s -u user:password "http://test.json.output" | python -c "import json,sys;input=json.load(sys.stdin);print (input.get('messages'))"

A reasonably short, pure python way to do this is with the requests library, but that's not built into python, and I find one-liners are only useful if they work across a lot of systems as-is:

import json,requests
r = requests.get("http://test.json.output/api/", auth=('user','pass'))
o = json.loads(r.content)
print (o.get('messages'))

1 comment:

Unknown said...

Where's the "one-liner" part?