美文网首页
python json的中文读取与中文写入

python json的中文读取与中文写入

作者: ltochange | 来源:发表于2021-07-29 20:19 被阅读0次

    写入json

    import json
    # 写入json
    all_res = {}
    write_path = "E:/test_feature.json"
    all_res["明天"] = "天气好"
    
    with open(write_path, "w", encoding='utf-8') as f:
        json.dump(all_res, f, ensure_ascii=False)
    

    打开文件test_feature.json,写入的内容为:

    {"明天": "天气好"}
    

    中文的写入 json.dump需要加上ensure_ascii=False参数。否则默认写入unicode

    {"\u660e\u5929": "\u5929\u6c14\u597d"}
    

    这里 查询不同编码之间的转换:

    在这里插入图片描述

    读取json

    write_path = "E:/test_feature.json"
    with open(write_path, encoding="utf-8") as f:
        res = json.load(f)
        print(type(res))
        print(res['明天'])
    

    读取文件时,需要加上encoding="utf-8",否则会出现错误UnicodeDecodeError: 'gbk' codec can't decode byte 0xbd in position 20: illegal multibyte sequence

    <class 'dict'>
    天气好
    

    相关文章

      网友评论

          本文标题:python json的中文读取与中文写入

          本文链接:https://www.haomeiwen.com/subject/xqyfvltx.html