I love Tori Black I love Tori Black - 1 year ago 84
JSON Question

Map a .json file into a dictionary

Ahoy there lads, I am in need of some help. I have a JSON file exactly like this:

"name": "Tori Black",
"age": "27",
"hobbies": "Skiing",
"name": "Jenna Jameson",
"age": "42",
"hobbies": "Jumping"



I want a python dictionary such that:

>> my_dict["Tori Black"]
>> [27, "Skiing"]

Basically I am turning the names into the keys for the dictionary and the values associated with that key are the two lines below the name element (age and hobbies, can always assume the age and hobbies are linked with the name above it). I am quite stuck, how do I do this?

Here is my attempt:

my_dict = dict([elem[1], elem[2]] for elem in open('data.json'))

Answer Source

your json file is not a valid mapping ... you cannot have duplicate keys in a json mapping ... you will need to manually iterate over the lines ... this solution assumes your file is laid out exactly the same as your example

def get_items(fname):
   with open(fname) as fh:
       for line in fh:
            if line.strip().startswith('"name"'):
               key = line.split(":")[-1].strip('" \n,')
               yield key,[next(fh).split(":")[-1].strip('" \n,') for _ in range(2)]

my_dict = dict(get_items("badjson.json"))
print my_dict["Jenna Jameson"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download