python中的json库怎么使用

41次阅读
没有评论

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

在 Python 中,可以使用 json 模块来处理 JSON 数据。下面是一些常见的 json 库的使用示例:

  1. 将 Python 对象转换为 JSON 字符串:
import json
data = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
json_data = json.dumps(data)
print(json_data)
  1. 将 JSON 字符串转换为 Python 对象:
import json
json_data = '{"name":"Alice","age": 25,"city":"New York"}'
data = json.loads(json_data)
print(data)
  1. 将数据写入 JSON 文件:
import json
data = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
with open('data.json', 'w') as file:
json.dump(data, file)
  1. 从 JSON 文件中读取数据:
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)

这些是 json 库的一些基本用法,你可以根据具体的需求进一步探索。

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

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