json遍历
时间: 2023-07-02 22:04:44 浏览: 54
你可以使用Python内置的`json`模块来解析JSON格式的数据,并使用循环或递归来遍历JSON对象。
例如,假设有以下JSON字符串:
```json
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": ["reading", "gaming", "traveling"],
"grades": {
"math": 90,
"english": 85,
"history": 95
}
}
```
你可以使用以下代码来遍历它:
```python
import json
# 将JSON字符串解析为Python对象
data = json.loads('{"name": "John", "age": 30, "city": "New York", "hobbies": ["reading", "gaming", "traveling"], "grades": {"math": 90, "english": 85, "history": 95}}')
# 遍历JSON对象
for key, value in data.items():
if isinstance(value, dict):
# 如果值是一个字典,递归遍历它
print(key + ":")
for inner_key, inner_value in value.items():
print(" " + inner_key + ": " + str(inner_value))
elif isinstance(value, list):
# 如果值是一个列表,遍历它
print(key + ":")
for item in value:
print(" " + str(item))
else:
# 否则,直接输出键值对
print(key + ": " + str(value))
```
输出结果为:
```
name: John
age: 30
city: New York
hobbies:
reading
gaming
traveling
grades:
math: 90
english: 85
history: 95
```
注意,上述代码假设JSON对象是一个嵌套的字典和列表结构。如果JSON对象的结构不同,你需要相应地调整代码来适应它。