Wednesday, March 17, 2010

March Madness Day 17

Experimentation with representations of JSON in Python. This program takes some test data in a file of formatted JSON data from stdio and loads it into memory and then prints out the version in memory.

testdata.json

{"foo":"bar", "baz":1, "a":2}


jsonstdio.py

import sys
import json

def getjson(jd):
jsondata = json.loads(jd)
print "JSON Data: "
print repr(jsondata)


def main():
stdin = sys.stdin.read()
getjson(stdin)

if __name__=="__main__":
main()




How to run:
python jsonstdio.py < testdata.json

2 comments:

Dan said...

How would you access the "foo" object's value from the jsondata variable? How would you iterate over the keys present in jsondata?

I don't know python much, see...

Rick said...

Dan, it loads into a dictionary, and you get iterate with standard dictionary methods.