How to dump json without quotes in python

后端 未结 5 2166
孤街浪徒
孤街浪徒 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'(?<!: )"(\S*?)"', '\\1', json_string)
    

    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'(?<!: )"(\S*?)"'
    o = {"noquotes" : 127, "put quotes here" : "and here", "but_not" : "there"}
    s = json.dumps(o)
    s2 = json.dumps(o, indent=3)
    strip_s = re.sub(regex,'\\1',s)
    strip_s2 = re.sub(regex,'\\1',s2)
    
    print(strip_s)
    print(strip_s2)
    
    assert(json.loads(strip_s) == json.loads(s) == json.loads(strip_s2) == json.loads(s2) == object)
    

    Will raise a ValueError but prints what you want.

    0 讨论(0)
  • 2021-02-14 18:25

    Well, that's not valid json, so the json module won't help you to write that data. But you can do this:

    import json
    
    with open('es_hosts.json', 'w') as fp:
        data = ['a', 'b', 'c']
        fp.write(json.dumps(','.join(data)).replace('"', ''))
    

    That's because you asked for json, but since that's not json, this should suffice:

    with open('es_hosts.json', 'w') as fp:
        data = ['a', 'b', 'c']
        fp.write(','.join(data))
    
    0 讨论(0)
  • 2021-02-14 18:33

    Before doing a string replace, you might want to strip the quotation marks:

    print '"a,b,c"'.strip('"')
    

    Output:

    a,b,c
    

    That's closer to what you want to achieve. Even just removing the first and the last character works: '"a,b,c"'[1:-1].

    But have you looked into this question?

    0 讨论(0)
  • 2021-02-14 18:41

    Use python's built-in string replace function

    with open('es_hosts.json', 'w') as fp:
       json.dump(','.join(host_list.keys()).replace('\"',''), fp)
    
    0 讨论(0)
  • 2021-02-14 18:42

    Just use for loop to assign list to string.

    import json
    
    with open('json_file') as f:
        data = json.loads(f.read())
        for value_wo_bracket in data['key_name']:
            print(value_wo_bracket)
    

    Note there is difference between json.load and json.loads

    0 讨论(0)
提交回复
热议问题