简体   繁体   English

如何使用 python 遍历 jsons(字符串)的无键列表?

[英]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:我正在使用 json.dumps 并最终得到以下 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 "["我看到python试图遍历组成我的json的字符串中的字符,所以我的第一个值是“[”

Any help would be appreciated!任何帮助,将不胜感激!

json.dumps takes some data and turns it into a string that is the JSON representation of that data. json.dumps获取一些数据并将其转换为一个字符串,该字符串是该数据的 JSON 表示形式。

To iterate over the data, just iterate over it instead of calling json.dumps on it:要迭代数据,只需迭代它而不是调用json.dumps

# 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 :如果您想从 JSON 字符串返回my_data ,请使用json.loads

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM