python怎么取json中对应的值

47次阅读
没有评论

共计 1075 个字符,预计需要花费 3 分钟才能阅读完成。

可以使用 python 的 json 库来处理 json 数据。
首先,需要将 json 数据解码为 python 的字典对象。可以使用 json.loads() 函数来实现。例如:

import json
# 假设 json 数据存储在变量 data 中
data = '{"name":"Alice","age": 25,"city":"New York"}'
# 解码 json 数据为字典对象
json_data = json.loads(data)
print(json_data["name"]) # 输出 "Alice"
print(json_data["age"]) # 输出 25
print(json_data["city"]) # 输出 "New York"

如果 json 数据是存储在文件中的,可以使用 json.load() 函数来加载文件并解码为字典对象。例如:

import json
# 假设 json 数据存储在文件 data.json 中
with open("data.json") as file:
json_data = json.load(file)
print(json_data["name"]) # 输出 "Alice"
print(json_data["age"]) # 输出 25
print(json_data["city"]) # 输出 "New York"

如果 json 数据中包含嵌套的子对象或数组,可以使用 . 运算符来访问相应的值。例如:

import json
data = '{"name":"Alice","age": 25,"city":"New York","hobbies": ["reading","painting"]}'
json_data = json.loads(data)
print(json_data["hobbies"][0]) # 输出 "reading"
print(json_data["hobbies"][1]) # 输出 "painting"

需要注意的是,如果 json 数据中不存在对应的键,或者访问的嵌套值不存在,会抛出 KeyError 异常。可以使用 json_data.get(key) 方法来避免异常的发生,并在值不存在时返回None。例如:

import json
data = '{"name":"Alice","age": 25}'
json_data = json.loads(data)
print(json_data.get("name")) # 输出 "Alice"
print(json_data.get("city")) # 输出 None

以上是处理 json 数据的基本方法,根据具体的数据结构和需求,可以进行进一步的处理和操作。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-22发表,共计1075字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)