Python读写JSON文件的两种方式

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)

 案例:

import json

class JsonProcess():
    def __init__(self, file_path):
        self.file_path = file_path

    def read_json_dict2json(self):
        json_dict = None
        with open(self.file_path, 'r', encoding='utf_8') as fp:
            json_dict = json.load(fp)
        # print(type(json_dict))
        idx = 0
        for item in json_dict:
            print(idx, json_dict[item]["title"])
            if "comment" in json_dict[item]:
                print("----", idx, json_dict[item]["comment"])
            idx += 1

    def read_json_appendjson(self, new_data):
        json_dict = None
        with open(self.file_path, 'r', encoding='utf_8') as fp:
            json_dict = json.load(fp)
        print(type(json_dict))
        idx = 1
        for item in json_dict:
            idx += 1
        # append new data and write into a file.
        json_dict[("00"+str(idx))[-3:]] = new_data
        with open(self.file_path, 'w', encoding='utf_8') as fp:
            json.dump(json_dict, fp, ensure_ascii=False)
        print("append finished.")

json_path = "./blogs.json"
json_object = JsonProcess(json_path)
# ---------------
new_data ={
        "tags": "nlp",
        "title": "图解transformer | The Illustrated Transformer",
        "linkurl": "https://blog.csdn.net/qq_36667170/article/details/124359818",
        "comment": "超级详细的《The Illustrated Transformer》的翻译,原文:https://jalammar.github.io/illustrated-transformer/"
    }
json_object.read_json_appendjson(new_data)
print("--------print--------")
json_object.read_json_dict2json()

----。

posted @ 2023-07-26 16:39  倦鸟已归时  阅读(800)  评论(0编辑  收藏  举报