在Python中,可以使用json
模块来解析JSON字符串。可以通过将JSON字符串转换为字典或列表的形式,然后使用索引或键名来获取JSON中的特定值。
以下是一个示例代码,展示了如何获取JSON中的某个值:
import json # JSON字符串 json_str = '{"name": "John", "age": 30, "city": "New York"}' # 将JSON字符串解析为字典 data = https://www.yisu.com/ask/json.loads(json_str)'name'] age = data['age'] city = data['city'] # 打印结果 print(f'Name: {name}') print(f'Age: {age}') print(f'City: {city}')
输出结果:
Name: John Age: 30 City: New York
在上述示例中,首先将JSON字符串json_str
使用json.loads()
函数解析为字典形式的数据。然后,可以通过键名获取字典中的特定值。