Skip to content

Instantly share code, notes, and snippets.

@trajber
Last active August 29, 2015 14:01
Show Gist options
  • Save trajber/35aa16e7293c4397d49a to your computer and use it in GitHub Desktop.
Save trajber/35aa16e7293c4397d49a to your computer and use it in GitHub Desktop.
A simple utility to parse JSON files.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json, sys
lines=[]
for line in sys.stdin:
stripped = line.strip()
if not stripped: break
lines.append(stripped)
content=''.join([str(x) for x in lines])
json_content=json.loads(content)
for arg in sys.argv[1:]:
cont_aux=json_content
tokens=arg.split(".")
for i in range(len(tokens)):
if i==len(tokens)-1:
v=cont_aux[tokens[i]]
else:
cont_aux=cont_aux[tokens[i]]
if isinstance(v, list):
for j in v:
print j.encode('utf-8').strip()
elif isinstance(v, basestring):
print v.encode('utf-8').strip()
else:
print str(v).strip()
@trajber
Copy link
Author

trajber commented May 20, 2014

  • File 'example.json'
{
  "example": 1,
  "hello": {
      "world": 2
   }
}
$ cat example.json | spy.py example hello.world
1
2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment