如何使用Python读写JSON文件

1. 读取JSON文件

假设我们有一个名为 data.json 的文件,其内容如下:

{
  "name": "Alice",
  "age": 30,
  "city": "New York"
}
我们可以使用Python中的json模块来读取该文件并将其存储为Python对象。以下是一个读取JSON文件的示例代码:
import json

# 打开 JSON 文件
with open('data.json') as f:
    data = json.load(f)

# 打印读取的数据,可以看到读取的JSON数据被转换为Python字典对象
print(data)

2.写入JSON文件

假设我们有一个Python字典对象,我们想要将其写入JSON文件。以下是一个写入JSON文件的示例代码:

import json

# 定义字典对象
data = {
    
    
    "name": "Bob",
    "age": 25,
    "city": "Los Angeles"
}
# 写入 JSON 文件

with open('output.json', 'w') as f:
    json.dump(data, f)
    
# 读取写入的数据并打印
with open('output.json') as f:
    output_data = json.load(f)
    print(output_data)

猜你喜欢

转载自blog.csdn.net/xili1342/article/details/130085509