Python - Json export to txt adds unexpected characters/separators
Question: 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 ".


Answer: 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](http://docs.python.org/2/library/json.html#json.dump) (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.

