pokemongirl1234 pokemongirl1234 - 3 months ago 10
Python Question

Iterate through Json list object - Python

I have some JSON text I want to iterate through, formatted in the following way:

{
"itemsPerPage": 45,
"links": {
"next": "https://www.12345.com"
},
"list": [
{
"id": "333333",
"placeID": "63333",
"description": " ",
"displayName": "test-12345",
"name": "test",
"status": "Active",
"groupType": "Creative",
"groupTypeV2": "Public",
"memberCount": 1,
},
{
"id": "32423",
"placeID": "606",
"description": " ",
"displayName": "test123",
"name": "test",
"status": "Active",
"groupType": "Creative",
"groupTypeV2": "Private",
"memberCount": 1,
},


I am trying to iterate through this list, and grab the displayName, however my code won't recognize all of the different display names. Here is my code:

for i in range(len(json_obj['list'])):
if (json_obj['list'][i]['displayName'] == "some id"):
do stuff
else:
exit()


How can I fix the statement, in order to successfully loop through the json obj?

Answer

While the JSON you posted isn't valid, I'll assume you left some stuff off the end.

for entry in dataset['list']:
    print(entry['displayName'])

Will loop through your JSON data.

If you want to do_stuff() if it matches a certain value:

for entry in dataset['list']:
    if entry['displayName'] == 'test-12345':
        do_stuff()
Comments