【问题标题】:how to write and read unicode to json file in python如何在python中将unicode写入和读取到json文件
【发布时间】:2020-08-02 02:44:18
【问题描述】:

我正在尝试使用 python3 将我的数据的字典类型保存到 txt 文件的 json 文件中。
以我的数据形式为例:

listdic = []
dic1 = {"id": 11106, "text": "*Kỹ_năng đàm_phán* , thuyết_phục"}
dic2 = {"id": 11104, "text": "*Ngoại_hình ưa_nhìn* , nhanh_nhẹn , giao_tiếp tốt"}
dic3 = {"id": 10263, "text": "giao_tiếp tốt"}

listdic.append(dic1)
listdic.append(dic2)
listdic.append(dic3)

我希望它像这样保存到我的 json 文件中:

我在互联网上阅读了一些解决方案并尝试了:

f = open("job_benefits.json", "a", encoding= 'utf-8')

for i in listdic:
    i = json.dumps(i)
    f.write(i + '\n')
f.close()

但我得到的结果是这样的:

然后我尝试读取文件,这是我的结果:

f = open("job_benefits.json", "r", encoding= 'utf-8')

listdic = f.readlines()
for i in listdic:
    print(i)

这不是我想要的将数据写入和读取到 json 文件的方式,有些机构可以帮助解决这种情况??
非常感谢您对我的语法感到抱歉!

【问题讨论】:

标签: python json unicode jupyter


【解决方案1】:

您正在使用 json 模块保存文件并将其作为文本读回,而不是尝试解码读取的 json 数据。因此,所有为防止信息丢失而进行转义编码的字符都保持转义编码。

您可以强制 json 输出 utf-8 编码,而不是通过传递 dumpsdump ensure_ascii=False 参数来自动转义所有非 ASCII 字符:

f = open("job_benefits.json", "a", encoding= 'utf-8')

for i in listdic:
    i = json.dumps(i, ensure_ascii=False)
    f.write(i + '\n')
f.close()

在您回读您的行后从 JSON 解码:

import json 

f = open("job_benefits.json", "r", encoding= 'utf-8')

listdic = f.readlines()
for i in listdic:
    print(json.loads(i))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-04
    • 2017-09-07
    • 2015-03-24
    • 2022-01-07
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多