【问题标题】:How to dump json-like string without quoting keys?如何在不引用键的情况下转储类似 json 的字符串?
【发布时间】:2018-06-10 21:10:35
【问题描述】:

而不是这个(来自json.dumps):

[
  {
    "created": 581937573,
    "text": "asdf"
  },
  {
    "created": 581937699,
    "text": "asdf"
  }
]

我想得到这个 [非 JSON] 输出:

[
  {
    created: 581937573,
    text: "asdf"
  },
  {
    created: 581937699,
    text: "asdf"
  }
]

如果json.dumps 可以选择更改键的引号字符,我可以将其设置为占位符并稍后将其删除。不幸的是,它似乎没有这个选项......还有其他聪明的想法吗?

(不需要从这种格式加载,但如果存在解决方案会很有趣)

【问题讨论】:

  • 请注意,虽然这在 JavaScript 本身中是有效的,但它是 not 有效的 JSON。

标签: python json python-3.x


【解决方案1】:

re.sub 在某些假设下提供快速修复:

import re

data = [...]
json_data = json.dumps(data)

with open('file.txt', 'w') as f:
    f.write(re.sub(r'"(.*?)"(?=:)', r'\1', json_data))

file.txt

[
  {
    created: 581937573,
    text: "asdf"
  },
  {
    created: 581937699,
    text: "asdf"
  }
]

这些假设是

  1. 您的数据足够小,re.sub 可以在合理的时间内运行
  2. 您的数据不包含字符串值,这些值本身包含的内容可能与我在此处使用的模式匹配。

该模式有效地查找所有字典键并去掉引号。

【讨论】:

  • 谢谢,这行得通。这里有一个额外的括号json_data)))。另外,能否请您简单地解释一下正则表达式部分(r'"(.*?)"(?=:)', r'\1')?
  • @dtgq 谢谢。它使用正则表达式来搜索双引号内的字符串,其中也恰好有一个冒号,并删除双引号。
【解决方案2】:

如果@cs95 的解决方案不适用于您的情况(例如,您在值中有额外的"),那么您可以使用jsonnetfmt 工具来执行此操作。这是一种解决方法,但效果很好。

jsonnetfmt 会将其格式化为 jsonnet,在这种情况下,这恰好是 OP 想要的。有点可配置,运行jsonnetfmt --help查看。

(请注意以下示例中的附加逗号,这是该方法的副作用)

安装步骤:

  1. 安装go
  2. 通过运行安装jsonnetfmt
go get github.com/google/go-jsonnet/cmd/jsonnetfmt

运行步骤:

  1. 将 json 保存到文件中。

  2. 在这个文件上运行jsonnetfmt

  3. 读取文件。

with open('json_file.json', 'w', encoding='utf8') as f:
    json.dump(json_data, f, ensure_ascii=False, indent=2)


from subprocess import run
run('jsonnetfmt json_file.json --in-place')


with open('json_file.json', 'r', encoding='utf8') as f:
    json_output= f.read()

之前:

[
  {
    "created": 581937573,
    "text": "asdf"
  },
  {
    "created": 581937699,
    "text": "asdf"
  }
]

之后:

[
  {
    created: 581937573,
    text: 'asdf',
  },
  {
    created: 581937699,
    text: 'asdf',
  },
]

之后加上--string-style d:

[
  {
    created: 581937573,
    text: "asdf",
  },
  {
    created: 581937699,
    text: "asdf",
  },
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多