温馨提示×

python的json库怎么使用

小亿
81
2023-12-16 02:13:15
栏目: 编程语言

使用Python的json库可以很方便地处理JSON数据。下面是一些使用json库的常见操作:

  1. 导入json库:
import json
  1. 将JSON字符串转换为Python对象(字典或列表):
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
print(data)  # 输出:{'name': 'John', 'age': 30, 'city': 'New York'}
  1. 将Python对象转换为JSON字符串:
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_str = json.dumps(data)
print(json_str)  # 输出:{"name": "John", "age": 30, "city": "New York"}
  1. 从文件中读取JSON数据:
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)
  1. 将数据写入JSON文件:
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as file:
    json.dump(data, file)

这些是json库的一些基本用法,可以根据具体需求进行更复杂的操作。更多详细的用法可以查看官方文档:https://docs.python.org/3/library/json.html

0