【问题标题】:saving json adds backslashes [duplicate]保存json会添加反斜杠[重复]
【发布时间】:2021-07-30 05:35:41
【问题描述】:
 jsonContent = json.dumps(myDict, default=convert)
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(jsonContent, f, ensure_ascii=False, indent=4)
    return jsonContent

我这样做是为了将字典转换为 json 并将其保存在文件中。如果我尝试用 Python 打印 json,我会得到一个未格式化的字典,如下所示:

myDict = {'first': {'phone': 1900, 'desktop': 1577, 'tablet': 148, 'bot': 9, 'other': 1}},

这还可以。但是当我打开文件时,我会看到如下内容:

"{\"first\": {\"phone\": 1900, \"desktop\": 1577, \"tablet\": 148, \"bot\": 9, \"other\": 1}´}"

如何删除所有反斜杠并在 Python 和保存的文件中正确格式化?

【问题讨论】:

  • 反斜杠是 JSON 所需的双引号字符的转义。
  • 没有它们我们不能打印吗?或者只是在 Python 打印输出或 .json 文件 @TomServo 中“美化”它们
  • 你为什么要进行两次 JSON 编码?
  • 当然你可以美化他们。你可以用字符串做任何你喜欢的事情。我的意思是,正如其他人指出的那样,您已经对其进行了两次编码。还不如在上面运行一堆字符串替换()。
  • 明确地说,您应该只对数据编码一次。您在第一行调用一次json.dumps(),在第三行再次调用json.dump()。只做一个或另一个,不要两个都做。现在,您正在创建一个需要解码两次才能获取原始数据的文件(第一次撤消第 3 行的json.dump(),第二次撤消第 1 行的json.dumps())。

标签: python json python-3.x dictionary


【解决方案1】:

如果您不想使用反斜杠,请像这样写入您的 json 文件

import json
myDict = {"first": {"phone": 1900,"other": 1}, "second": {"adwords": 1419, "no_om_source": 1223}}
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(myDict, f, ensure_ascii=False, indent=4)

【讨论】:

    猜你喜欢
    • 2017-05-12
    • 2016-06-14
    • 2011-01-11
    • 2014-10-14
    • 1970-01-01
    • 2015-10-23
    • 2020-02-01
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多