Search code examples
pythonjsonnewlinepretty-print

Python dumps "\n" instead of a newline in a json file


I have been taking some data through the Graph API of facebook and saving it in the json format in a new file. However, whenever I try to save it in the file, the new lines don't actually show as newlines but they show as "\n". Moreover, a backslash also is appended before any data.

For example,

I want the data to be saved in this format:

{
"feed": {
"data": [
{
"message": "XYZ",
"created_time": "0000-00-0000:00:00+0000",
"id": ABC"
}

But it is being saved in this format (in a single line)

"{\n\"feed\": {\n\"data\": [\n{\n\"message\": \"XYZ\",\n\"created_time\": \"0000-00-0000:00:00+0000\",\n\"id\": \"ABC\"\n}

How do I save it in the first format and not the second?

I have been using this code:

url2 = '{0}?fields={1}&access_token={2}'.format(url,fields,token) #the format in which the API receives the request to get the data which is needed
# token is the access token, url is to connect to fb and fields is the data I want
size = os.path.getsize('new.json') #gets the size of the file 
content = requests.get(url2).json()  #obtaining the content 
obj = json.dumps(content,indent = 4) 

with open('new.json','r+') as f:    #if file size is 0, delete all content and rewrite with new and old content 
    if size>0:
        f.truncate(0)
    json.dump(obj,f)

Even though I have used indent, it does not pretty-print in the way I want it to. Help appreciated!


Solution

  • You're using json.dumps to create a JSON representation of your data. Then you're using json.dump to create a JSON representation of that representation. You're double-JSONifying it. Just use one or the other.