Home > front end >  How can I iterate through a keyless list of jsons (string) with python?
How can I iterate through a keyless list of jsons (string) with python?

Time:07-06

I am using json.dumps and end up with the following json:

[{
"name": "Luke",
"surname": "Skywalker",
"age": 34
},
{
"name": "Han",
"surname": "Solo",
"age": 44
},
{
...
...}]

I would like to iterate through this list and get a person on each iteration, so on the first iteration I will get:

{
"name": "Luke",
"surname": "Skywalker",
"age": 34
}

All the examples I've seen so far are iterating using a key, for example:

for json in jsons['person']:

But Since I dont have a "person" key that holds the persons data, I have nothing to iterate through but the object structure itself or everything that is inside the - {}

When I optimistically tried:

for json in jsons

I saw that python attempted to iterate through the chars in the string that made up my json, so my first value was "["

Any help would be appreciated!

CodePudding user response:

json.dumps takes some data and turns it into a string that is the JSON representation of that data.

To iterate over the data, just iterate over it instead of calling json.dumps on it:

# Wrong!
my_data = [...]
jsons = json.dumps(my_data)
for x in jsons:
   print(x)  # prints each character in the string

# Correct:
my_data = [...]
for x in my_data:
   print(x)  # prints each item in the list.

If you want to go back to my_data from a JSON string, use json.loads:

jsons = "[{}, {}]"
my_data = json.loads(jsons)
for x in my_data:
   print(x)  # prints each item in the list.
  • Related