简体   繁体   English

如何在不引号的情况下转储类似json的字符串?

[英]How to dump json-like string without quoting keys?

Instead of this (from json.dumps ): 代替这个(来自json.dumps ):

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

I would like to get this [non-JSON] output: 我想获得此[non-JSON]输出:

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

If json.dumps had an option to change the quote character for keys, I could just set it to a placeholder and strip them out later. 如果json.dumps可以更改键的引号字符,则可以将其设置为占位符,然后将其剥离。 Unfortunately it doesn't appear to have this option... any other clever ideas? 不幸的是,它似乎没有这个选择……还有其他聪明的主意吗?

(load from this format is not necessary, but would be interesting if a solution for it exists as well) (从这种格式加载不是必需的,但如果也有解决方案,这将很有趣)

re.sub offers a quick fix under certain assumptions: 在某些假设下, 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"
  }
]

These assumptions are 这些假设是

  1. your data is small enough that re.sub runs in a reasonable amount of time 您的数据足够小,因此re.sub可以在合理的时间内运行
  2. your data does not contain string values that themselves contain stuff that could match the pattern I've used here. 您的数据不包含字符串值,这些字符串值本身包含的内容可能与我在此使用的模式匹配。

The pattern effectively looks for all dictionary keys and strips out the quotes. 该模式有效地查找了所有字典键并去除了引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM