tags:

views:

270

answers:

2

I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.

I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do a simple print that verifies I got the data.

I'm trying to figure out how to actually work with a given JSON object in Python. In javascript, its as simple as

var x = {'asd':'bob'}
alert( x.asd ) //alerts 'bob'

Accessing the various properties on an object is simple dot notation. What's the equivalent for Python?

So this is my code that is doing the import. I'd like to know how to work with the individual objects stored in the list.

#! /usr/local/bin/python2.6

import os, json

#define path to reports
reportspath = "reports/"

# Gets all json files and imports them

dir = os.listdir(reportspath)

jsonfiles = []

for fname in dir:
    with open(reportspath + fname,'r') as f:
     jsonfiles.append( json.load(f) )

for i in jsonfiles:
    print i #prints the contents of each file stored in jsonfiles
+4  A: 

What you get when you json.load a file containing the JSON form of a Javascript object such as {'abc': 'def'} is a Python dictionary (normally and affectionately called a dict) (which in this case happens to have the same textual representation as the Javascript object).

To access a specific item, you use indexing, mydict['abc'], while in Javascript you'd use attribute-access notation, myobj.abc. What you get with attribute-access notation in Python are methods that you can call on your dict, for example mydict.keys() would give ['abc'], a list with all the key values that are present in the dictionary (in this case, only one, and it's a string).

Dictionaries are extremely rich in functionality, with a wealth of methods that will make your head spin plus strong support for many Python language structures (for example, you can loop on a dict, for k in mydict:, and k will step through the dictionary's keys, iteratively and sequentially).

Alex Martelli
Are there any easy ways to pretty print a json object, only showing the keys and no data? Would be great to make it easy to see the key structure of such an object
Geuis
Well, it's not really a json object once you've loaded it...it's a dict. But anyway try "print mydict.keys()"
Therms
import pprint; pprint.pprint(mydict.keys())
monkut
... which is just a list of keys anyway so pprint doesn't given you anything extra :p
monkut
A: 

To access all properties, try eval() statement before append a list.

like:

import os

#define path to reports
reportspath = "reports/"

# Gets all json files and imports them

dir = os.listdir(reportspath)


for fname in dir:
    json = eval(open(fname).read())
    # now, json is a normal python object
    print json
    # list all properties...
    print dir(json)
olarva
This works, and if you use `repr()` on the resulting object you get the JSON back again. However! It is much better to use the JSON library; `eval()` is a horrible security hole; if you download some JSON from the Internet, it might contain dangerous code. And you can put native Python stuff in your dict, which `repr()` might string-ize in ways that would confuse JSON; for example, if you put a tuple in your dict, the result won't be legal JSON. (JSON has lists, in square braces "[]", but does not have tuples in parentheses.)
steveha
Thanks for comments."eval() is a horrible security hole"Yes! if source is unsafe.
olarva