Python读写JSON文件的两种方式

发布时间 2023-07-26 16:45:09作者: 倦鸟已归时

1. 把文件读取为字符串,然后转换为json数据(dict格式),loads and dumps

关键点:写入json文件的时候,要指定ensure_ascii参数为False,否则中文编码虽然为utf_8,但仍然无法显示中文,而是\uxxx形式的编码。new_json_string = json.dumps(json_data, ensure_ascii=False)

import json

def read_json_str2dic(path):
    json_str = None  # json string
    with open(path, 'r', encoding='utf_8') as fp:
        json_str = fp.read()
    json_data = json.loads(json_str)  # get json from json string
    print(type(json_data))  # <class 'dict'>
    for item in json_data:
        print(item)  # print keys of json_data
        print(json_data[item])  # print values of json_data

    # append new data and write into a file.
    new_data = {
        "tags": "工业检测", 
        "title":"【总结】全面解析机器视觉在工业检测中应用瓶颈",
        "linkurl":"https://mp.weixin.qq.com/s/SeqVZUqVC_y7pUO2xWcqqQ",
        "comment":"给出了很多思考,值得反复看。", 
    }
    json_data["003"] = new_data
    # new_json_string = json.dumps(json_data)  # 会把中文转为\uxxx形式
    new_json_string = json.dumps(json_data, ensure_ascii=False)  # 正常显示中文
    with open("./new_blogs.json", 'w', encoding='utf_8') as nf:
        nf.write(new_json_string)

if __name__ == '__main__':
    json_path = "./blogs.json"
    read_json_str2dic(json_path)

2.字典类型和JSON数据互相转换。load and dump

def read_json_dict2json(path):
    json_dict = None
    with open(path, 'r', encoding='utf_8') as fp:
        json_dict = json.load(fp)
    print(type(json_dict))
    for item in json_dict:
        print(item)
        print(json_dict[item])
    # append new data and write into a file.
    new_data = {
        "tags": "工业检测", 
        "title":"【方案】基于机器视觉的锂电池表面缺陷检测方案",
        "linkurl":"https://mp.weixin.qq.com/s/1ZCjE1qoinqr0O1El8gOMA",
        "comment":"给出了很多思考,值得反复看。", 
    }
    json_dict["004"] = new_data
    with open(path, 'w', encoding='utf_8') as fp:
        json.dump(json_dict, fp, ensure_ascii=False)