How to retrieve property values from a JSON string?
In Python, you can use the json library to parse a JSON string and retrieve its attribute values.
Assume we have the following JSON string:
import json
json_str = '{"name": "John", "age": 30, "city": "New York"}'
To obtain the values of the attributes, you can follow these steps:
- parse a JSON string into a Python object.
data = json.loads(json_str)
- obtain
name = data["name"]
age = data.get("age")
city = data.get("city")
Here is the complete code:
import json
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
name = data["name"]
age = data.get("age")
city = data.get("city")
print(name) # 输出: John
print(age) # 输出: 30
print(city) # 输出: New York
Note: If a property does not exist in a JSON string, accessing it using data[“property”] will raise a KeyError exception, while using the get() method will return either None or a specified default value.