温馨提示×

python中import json怎么使用

小亿
116
2024-01-08 23:44:23
栏目: 编程语言

在Python中,可以使用import json语句导入json模块,然后使用该模块中的函数和类来处理JSON数据。

下面是json模块的一些常用函数和类的示例用法:

  1. 将JSON字符串转换为Python对象:
import json

# JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串转换为Python对象
python_obj = json.loads(json_str)
print(python_obj)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
  1. 将Python对象转换为JSON字符串:
import json

# Python对象
python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python对象转换为JSON字符串
json_str = json.dumps(python_obj)
print(json_str)  # 输出: {"name": "John", "age": 30, "city": "New York"}
  1. 读取JSON文件并解析为Python对象:
import json

# 读取JSON文件
with open('data.json') as json_file:
    json_str = json_file.read()
# 解析JSON字符串为Python对象
python_obj = json.loads(json_str)
print(python_obj)
  1. 将Python对象写入JSON文件:
import json

# Python对象
python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
# 将Python对象转换为JSON字符串
json_str = json.dumps(python_obj)
# 将JSON字符串写入文件
with open('data.json', 'w') as json_file:
    json_file.write(json_str)

这些只是json模块的一些基本用法示例,json模块还提供了其他函数和类来处理更复杂的JSON数据,你可以查看官方文档来了解更多信息:json - Python标准库文档

0