1、读取json文件
import json
# 打开文件,'r'表示只读模式
with open('文件路径/文件名.json', 'r') as json_file:
# 逐行读取文件内容
for line in json_file:
try:
# 用 json.loads() 方法加载每行的JSON数据
data = json.loads(line)
# 现在,变量 data 包含了每行的JSON对象,可以按照字典的方式访问其中的数据
print(data)
except json.JSONDecodeError as e:
# 处理无效的JSON行
print(f"Error decoding JSON: {e}")
2、写入json文件
import json
# 要写入文件的 JSON 数据
data_to_write = {
"name": "John",
"age": 30,
"city": "New York"
}
# 打开文件,'w'表示写入模式
with open('文件路径/文件名.json', 'w') as json_file:
# 使用 json.dump() 方法将数据写入文件
#indent参数用于指定缩进的空格数,使文件更易读
json.dump(data_to_write, json_file, indent=2)