【问题标题】:Python/Json dump extra backslashes in data [duplicate]Python / Json在数据中转储额外的反斜杠[重复]
【发布时间】:2021-04-05 15:06:09
【问题描述】:

我的期望不正确吗? 所需的输出是针对单个字段的

"{\"escapeChar\":\"\\\", \"quoteChar\":\"\"\", \"separatorChar\":\",\"}"

输入 csv 文本

"{""escapeChar"":""\\"", ""quoteChar"":""\"""", ""separatorChar"":"",""}"

代码:

obj_str = json.dumps(table_obj).replace('RS Target Table', 'Table Name').replace('Stage Table', 'input_table')

#Get obj back with replacement  BANG!!
obj = json.loads(obj_str)

print ('after loads, source_serde_params: ',   obj['source_serde_params'])
with open(filename, 'w' ) as write_file:
                    json.dump(obj, write_file,  indent=2)

控制台:

after loads, source_serde_params:  {"escapeChar":"\\", "quoteChar":"\"", "separatorChar":","}

输出文件:

"source_serde_params": "{\"escapeChar\":\"\\\\\", \"quoteChar\":\"\\\"\", \"separatorChar\":\",\"}"

python 3.7.9 笔记本电脑

【问题讨论】:

  • 为什么将 JSON 放入 CSV 文件中?
  • 您想要的输出不是有效的 json。第一个 \ 将转义 " 并弄乱 json 的其余部分。此外,前导和尾随 " 不是有效 json 的一部分。
  • @RaniSharim,OP 希望他们的 JSON 文档由单个字符串组成。这样解释是有效的。

标签: python json backslash


【解决方案1】:

输出是正确的 - 只是您在一个环境中看到输出,它会在数据中向您显示任何实际的 \,以便它可以重用 \ 字符来表示其他字符的转义序列,例如',",n,t等等...

只需更改查看输出文件的方式即可查看其实际内容。 当您写下您在“控制台”中看到的内容时,您可能会看到交互式输出,它向您显示字符串的repr,其中反冲以这种方式使用;只需在已编码的 json 字符串周围加上 print (...) 即可查看其实际的、未转义的内容。

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2020-02-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多