Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading