Tampa
Tampa

Reputation: 78244

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

Upvotes: 26

Views: 71077

Answers (5)

kushal khanal
kushal khanal

Reputation: 1

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

Upvotes: 0

szmoore
szmoore

Reputation: 944

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.

Upvotes: 9

Jeff Sheffield
Jeff Sheffield

Reputation: 6306

Use python's built-in string replace function

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

Upvotes: 1

enrico.bacis
enrico.bacis

Reputation: 31484

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

Upvotes: 1

Falko
Falko

Reputation: 17867

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?

Upvotes: 21

Related Questions