TommasoF
TommasoF

Reputation: 825

Python - Json export to txt adds unexpected characters/separators

I'm trying to write a json object to a txt file to be used in an other program. The file generated by code presents unexpected behavior (in my opinion):

f = {'nt' : 50, 'nt_array': [10,20,30] }
json_obj = json.dumps(f)
f=open('out.txt','w')
f.write(json.dumps(json_obj)
f.close()

This code produce a txt file with the following content:

"{\"nt_array\": [10, 20, 30], \"nt\": 50}"

But I want this:

{"nt_array": [10, 20, 30], "nt": 50}

It adds some separators / and ".

Upvotes: 0

Views: 191

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

You encoded to JSON twice:

>>> import json
>>> obj = {'nt' : 50, 'nt_array': [10,20,30] }
>>> print json.dumps(obj)
{"nt_array": [10, 20, 30], "nt": 50}
>>> print json.dumps(json.dumps(obj))
"{\"nt_array\": [10, 20, 30], \"nt\": 50}"

Just use the json.dump() function (no s at the end) once and write directly to the file:

obj = {'nt' : 50, 'nt_array': [10,20,30] }
with open('out.txt','w') as f:
    json.dump(obj, f)

Note the use of with to have the file closed automatically as well.

Upvotes: 2

g.d.d.c
g.d.d.c

Reputation: 48018

You need to remove one of the calls to json.dumps. The first call gives you the value you want, the second call produces the escaped format that you don't want.

Upvotes: 0

Related Questions