简体   繁体   中英

How to dump json-like string without quoting keys?

Instead of this (from json.dumps ):

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

I would like to get this [non-JSON] output:

[
  {
    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. 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:

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
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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