Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump json without quotes in python

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

 "a,b,c"

I would like:

 a,b,c

Thanks

like image 569
Tampa Avatar asked Sep 01 '14 19:09

Tampa


People also ask

How do I remove a quote from a JSON string in Python?

Using the lstrip() function to remove double quotes from string in Python. The lstrip() function can remove characters from the start of the string. With this function, we can remove the double quotes from the start of the string.

Can JSON key be without quotes?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.

How do you dump a JSON file in Python?

Method 2: Writing JSON to a file in Python using json.dump() Another way of writing JSON to a file is by using json.dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.

Does JSON dump escape quotes?

Furthermore, all double quotes of the actual JSON formatting are escaped with a backslash.


2 Answers

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.

like image 52
szmoore Avatar answered Sep 17 '22 12:09

szmoore


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?

like image 31
Falko Avatar answered Sep 20 '22 12:09

Falko