Home > front end >  JSON output is including /n rather than line breaks
JSON output is including /n rather than line breaks

Time:04-05

How can the JSON output be formatting in a way that doesn't include the \n text, and instead shows these as new lines like intended. This is what the saved output file looks like:

enter image description here

...but this is what it should look like and how it looks when I use print

enter image description here

import requests
import json

def get_all_time_entries():

    url_address = "***"  
    headers = {
        "Authorization": "***",
        "api-version": "2020-01-31"
    }

    # find out total number of pages
    r = requests.get(url=url_address, headers=headers).json()
    total_pages = 605

    # results will be appended to this list
    all_time_entries = []

    # loop through all pages and return JSON object
    for page in range(1, total_pages):

        url = "***" str(page)              
        response = requests.get(url=url, headers=headers).json()        
        all_time_entries.append(response)       
        page  = 1

    # prettify JSON
    data = json.dumps(all_time_entries, sort_keys=True, indent=4)



    return data



#print(get_all_time_entries())

with open('appointmentsHistory.json', 'w', encoding='utf-8') as f:
    # note that I use dump method, not dumps
    json.dump(get_all_time_entries(), f, sort_keys=True, indent=4)

CodePudding user response:

json.dumps() transforms the data dictionary into a string, and then json.dump() writes the JSON representation of that string to the file.

To resolve, remove json.dumps() from the get_all_time_entries() method. json.dump() will take the dictionary in directly and transform it into a JSON string for you.

import requests
import json

def get_all_time_entries():
    url_address = "***"  
    headers = {
        "Authorization": "***",
        "api-version": "2020-01-31"
    }

    # find out total number of pages
    r = requests.get(url=url_address, headers=headers).json()
    total_pages = 605

    # results will be appended to this list
    all_time_entries = []

    # loop through all pages and return JSON object
    for page in range(1, total_pages):

        url = "***" str(page)              
        response = requests.get(url=url, headers=headers).json()        
        all_time_entries.append(response)       
        page  = 1

    return data

with open('appointmentsHistory.json', 'w', encoding='utf-8') as f:
    # note that I use dump method, not dumps
    json.dump(get_all_time_entries(), f, sort_keys=True, indent=4)

CodePudding user response:

json.dump() takes an object, you seem to be passing it a JSON-like string.

  • Related