How to dump json without quotes in python

后端 未结 5 2155
孤街浪徒
孤街浪徒 2021-02-14 17:59

Here is how I dump a file

with open(\'es_hosts.json\', \'w\') as fp:
  json.dump(\',\'.join(host_list.keys()), fp)

The results is



        
5条回答
  •  难免孤独
    2021-02-14 18:21

    To remove the quotation marks in the keys only, which may be important if you are parsing it later (presumably with some tolerant parser or maybe you just pipe it directly into node for bizarre reasons), you could try the following regex.

    re.sub(r'(?

    One issue is that this regex expects fields to be seperated key: value and it will fail for key:value. You could make it work for the latter with a minor change, but similarly it won't work for variable amounts of whitespace after :

    There may be other edge cases but it will work with outputs of json.dumps, however the results will not be parseable by json. Some more tolerant parsers like yaml might be able to read the results.

    import re
    regex = r'(?

    Will raise a ValueError but prints what you want.

提交回复
热议问题