JSON dump在使用某些字符时会破坏我的字典

2024-04-19 16:08:56 发布

您现在位置:Python中文网/ 问答频道 /正文

将数据转储到文件中json.dump文件. 数据如下所示:

{"hello": {"this": 1, "a": 1, "is": 1, "test": 1}}

我用来实现这一点的代码如下(worddict是一个文件,类似于文件.json)地址:

with open(words, 'w') as fp:
    json.dump(worddict, fp)
fp.close()

我想要这种格式的数据:

{
"hello": {
    "a": 1,
    "is": 1,
    "test": 1,
    "this": 1
}

我把代码改成:

with open(words, 'w') as fp:
    json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '))
fp.close()

在我尝试抛弃“Á”、“Ű”。。。 这些字符会打断worddict文件,当我对该文件进行cat时,它看起来是这样的:

{

知道为什么吗?你知道吗


Tags: 文件数据代码testjsonhelloisas
2条回答

我在python2和python3中运行了您的代码片段。 在python3中,它没有给我任何错误。你知道吗

我运行了以下代码:

import json

words = 'a.txt'
worddict = {"hello": {"this": 1, "a": 1, "is": 1, "test": "Á"}}
with open(words, 'w') as fp:
    json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '))

作为输出:

{
    "hello": {
        "a": 1,
        "is": 1,
        "test": "\u00c1",
        "this": 1
    }
}

但在python2中,我遇到了错误。我得到了一个描述错误的链接: http://www.python.org/peps/pep-0263.html

问题出现在python2中,默认情况下python2字符串不是unicode。所以您必须在源代码文件的顶部提到编码。 在python源代码开始之前,我在文件的顶部添加了“#coding=UTF-8”,以便让python解释器知道文件的编码。一旦我这样做了,代码就在python2和python3中运行,没有任何错误。 我得到以下输出:

{
    "hello": {
        "a": 1,
        "is": 1,
        "test": "\u00c1",
        "this": 1
    }
}

这是我最后使用的完整源代码。你知道吗

# coding=UTF-8

import json

words = 'a.txt'
worddict = {"hello": {"this": 1, "a": 1, "is": 1, "test": "Á"}}
with open(words, 'w') as fp:
    json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '))

替换

    json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '))

    json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)

相关问题 更多 >