How to dump json without quotes in python

This is how I upload the file

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

      

results

 "a,b,c"

      

I would like to:

 a,b,c

      

thank

+3


source to share


4 answers


Before doing string replacement, you may want strip

quotes:

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

      

Output:



a,b,c

      

This is closer to what you want to achieve. Even simply removing the first and last characters works: '"a,b,c"'[1:-1]

.

But have you looked into this question ?

+2


source


Use python inline string replace function



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

      

0


source


Well, this is invalid json, so the module json

won't help you write this 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('"', ''))

      

This is because you asked json

, but since it is not json, this should be sufficient:

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

      

0


source


To remove quotes in keys only, which might be important if you parse it afterwards (presumably with some tolerant parser, or perhaps just pipe it directly to node

for unusual reasons), you can try the following regex.

re.sub(r'(?<!: )"(\S*?)"', '\\1', json_string)

      

One problem is that this regex expects fields to be split key: value

and it will fail for key:value

. You can make it work for the latter with minor modifications, but in a similar way it will not work for variable number of spaces after:

There may be other cases of edges, but it will work with pins json.dumps

, however the results will not be parsed by json. Some more bearable parsers like yaml

that might 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 pick up ValueError

but print what you want.

0


source







All Articles