Dzerlig
Dzerlig

Reputation: 247

how do i parse json file using python

After doing a rest api call and storing result as json file contents of json file look as follows:

["x","y","z"]

I need to use python script to iterate through each item and print it out.

I have the following snippet of code which does error out.

with open('%s/staging_area/get_label.json' % cwd) as data_file:
		data = json.load(data_file)
for item in data:
	print data [item]

Error I am getting is as follows:

Traceback (most recent call last):
  File "Untitled 8.py", line 33, in <module>
    print data [item]
TypeError: list indices must be integers, not unicode

What am I missing? Thank you for your help!

Upvotes: 0

Views: 69

Answers (1)

Henry
Henry

Reputation: 15732

In the line

for item in data:

you set item to be an element of data, but then in the line

print data [item]

you use item as an index, which it is not. Hence the error. There is also no need to use an index since item is already an element of data.

What you can do instead is:

for item in data:
    print(item)

Upvotes: 3

Related Questions