【问题标题】:Unneeded backslashes when in json dumps method在 json 转储方法中不需要的反斜杠
【发布时间】:2020-07-23 18:24:26
【问题描述】:
print(keystr)
print(addstr10)
dict[keystr] = addstr10
json.dump(dict, json_file, indent=2)

这会产生 keystr = nested_object 对于 addstr10 它产生

{"another_nested_object": {          "another_another_nested_object": "ymwjkxpr",          "integervalue" : 11,          "floatvalue" : 4.703165912962773,          "anothernamer" : True,          "another_nested_object_1": {                  "another_key": "vbiofdhz"          }       }     }

看起来不错,但 json 文件在值对中有额外的反斜杠,我想去掉它

{
  "nested_object": "{\"another_nested_object\": {          \"another_another_nested_object\": \"ymwjkxpr\",          \"integervalue\" : 11,          \"floatvalue\" : 4.703165912962773,          \"anothernamer\" : True,          \"another_nested_object_1\": {                  \"another_key\": \"vbiofdhz\"          }       }     }"
}

【问题讨论】:

  • 我不明白这个问题。 json.dumps() 将始终在字符串周围加上引号。
  • 为什么nested_object的值是字符串而不是字典?
  • 我希望 "another_nested_object" 在输出中像在值对中一样有引号。
  • 应该这样做。请发布一些实际代码,很难从您发布的内容中判断出了什么问题。
  • 刚刚更新了我的总结

标签: python json string-literals


【解决方案1】:

原因是addstr 已经编码为 JSON。因此,当您将其作为值包含在字典中时,您将对其进行第二次编码。

你应该先解码,所以改变

dict[keystr] = addstr10

dict[keystr] = json.loads(addstr10)

但是,嵌套对象包含无效的 JSON。 JSON 使用 truefalse 作为布尔值,但您的字符串有 True,无法正确解析。

您可以尝试使用ast.literal_eval() 而不是json.loads()

import ast
dict[keystr] = ast.literal_eval(addstr10)

【讨论】:

  • dict[keystr] = json.loads(addstr10) dict[keystr] = addstr10 json.dump(dict, json_file, indent=2) 你指的是这个吗?如果是这样,它会给我一个运行时错误
  • x = json.loads(addstr8) 文件“C:\Users\williamzhang88\AppData\Local\Programs\Thonny\lib\json_init_.py”,第 348 行,在加载返回 _default_decoder.decode(s) 文件“C:\Users\williamzhang88\AppData\Local\Programs\Thonny\lib\json\decoder.py”,第 337 行,在解码 obj 中,end = self.raw_decode(s , idx=_w(s, 0).end()) 文件“C:\Users\williamzhang88\AppData\Local\Programs\Thonny\lib\json\decoder.py”,第 353 行,在 raw_decode obj 中,end = self .scan_once(s, idx)
  • 嵌套对象是无效的 JSON。 True 应该是 true
猜你喜欢
  • 2014-01-31
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 2011-03-23
相关资源
最近更新 更多