You can use thejson
module in Python to parse JSON format data and convert it into a dictionary or list object in Python. For traversing key-value pairs in JSON data, we can implement it through dictionary or list traversal in Python.
For example, for the following JSON formatted data:
{ "name": "Alice", "age": 25, "skills": ["Python", "Java", "C++"], "address": { "city": "Beijing", "country": "China" } }
We can use thejson
module and theloads()
function to convert it into a Python Dictionary object in:
import json data = '{"name": "Alice", "age": 25, "skills": ["Python", "Java", "C++"], "address": {"city": "Beijing", "country": "China"}}' result = json.loads(data)
Next, we can traverse all key-value pairs through theitems()
method of the dictionary:
for key, value in result.items(): print(key, value)
The above code will be in sequence Output the following:
name Alice
age 25
skills ['Python', 'Java', 'C ']
address {'city': 'Beijing', 'country': 'China'}
In addition, for nested dictionaries, we can also access child elements through multiple key access:
print(result['address']['city']) # 输出'Beijing'
For JSON format We can access the array elements in the data through list traversal:
for skill in result['skills']: print(skill)
The above code will output the following content in sequence:
Python
Java
C
In short, in Python, you can traverse key-value pairs in JSON format data through dictionary or list traversal. The specific traversal method depends on whether you get a dictionary object or a dictionary object after parsing the JSON data. A list object, and the structure of the JSON data.
1. Return a list of key-value pairs by calling the items of the dictionary, and then use the key and value variables to receive the data contained in the list respectively. keys and values.
2. Finally, access the key values one by one in the for loop through the key and value variables.
Example
age = { 'Tom': 18, 'Jerry': 12, 'Bob': 23, 'Ann': 31 } for key, value in age.items(): print(f"Key:{key},Value:{value}") # output: # Key:Tom,Value:18 # Key:Jerry,Value:12 # Key:Bob,Value:23 # Key:Ann,Value:31
The above is the detailed content of How to use json data key-value pair traversal in Python. For more information, please follow other related articles on the PHP Chinese website!