写一个简单的json的方法并读取
1.创建
import json
# 要写入 JSON 文件的数据
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 指定要写入的 JSON 文件路径
file_path = "data.json"
# 将数据写入 JSON 文件
with open(file_path, "w") as json_file:
json.dump(data, json_file, indent=4)
print("JSON 文件已创建并写入数据。")
2.读取
import json
# 指定要读取的 JSON 文件路径
file_path = "data.json"
# 读取 JSON 文件并解析数据
with open(file_path, "r") as json_file:
data = json.load(json_file)
#这里可以用字典访问的方式读取比如data["name"]
# 打印解析后的数据
print("解析后的数据:")
print(data)