PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

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

 July 25, 2022     json, python     No comments   

Issue

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!


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.


Answered By - AKX
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing