Sam
Sam

Reputation: 31

Python: Json.load gives list and can't parse data from it

I have a data.json file, which looks like this:

["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]

I am trying to get "Event" from this file using python and miserably failing at this.

with open('data.json', 'r') as json_file:
    data = json.load(json_file)
    print (data['Event'])

I get the following error:

TypeError: list indices must be integers or slices, not str

And even when I try

print (data[0]['Event'])

then I get this error:

TypeError: string indices must be integers

One more thing:

print(type(data))

gives me "list"

I have searched all over and have not found a solution to this. I would really appreciate your suggestions.

Upvotes: 1

Views: 4073

Answers (3)

C.Nivs
C.Nivs

Reputation: 13106

You could use the ast module for this:

import ast

mydata = ["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
data = ast.literal_eval(mydata[0])
data
{'Day': 'Today', 'Event': '1', 'Date': '2019-03-20'}

data['Event']
'1'

Edit

Your original code does load the data into a list structure, but only contains a single string entry inside that list, despite proper json syntax. ast, like json, will parse that string entry into a python data structure, dict.

As it sits, when you try to index that list, it's not the same as calling a key in a dict, hence the slices cannot be str:

alist = [{'a':1, 'b':2, 'c':3}]
alist['a']
TypeError

# need to grab the dict entry from the list
adict = alist[0]
adict['a']
1

Upvotes: 4

TomMP
TomMP

Reputation: 815

Your problem is that you are parsing it as a list that consists of a single element that is a string.

["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]

See how the entire content of the list is surrounded by " on either side and every other " is preceded by a \? The slash generally means to ignore the special meaning the following character might have, but interpret it as purely a string.

If you have control over the file's contents, the easiest solution would be to adjust it. You will want it to be in a format like this:

[{"Day":"Today", "Event": "1", "Date": "2019-03-20"}]

Edit: As others have suggested, you can also parse it in its current state. Granted, cleaning the data is tedious, but oftentimes worth the effort. Though this may not be one of those cases. I'm leaving this answer up anyway because it may help with explaining why OPs initial attempt did not work, and why he received the error messages he got.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82755

You need to convert the elements in data to dict using json module.

Ex:

import json

with open(filename) as infile:
    data = json.load(infile)
for d in data:
    print(json.loads(d)['Event'])

Or:

data = list(map(json.loads, data))
print(data[0]["Event"])

Output:

1

Upvotes: 1

Related Questions