How enter line space into a json file

1.3k Views Asked by At

I have a json file which the contains list of dictionaries. Here is a sample of data

   "[{'id': 1, 'name': 'jasmin', 'rel': []}, {'id': 10, 'name': 'Dhoya', 'rel':    [{'id':3, 'name': 'ana', 'rel': [{'id': 4, 'name': 'ash', 'rel': []}]}]}]"

I have created this json file by adding item to a dictionary and appending items of rel. and then I have append each dictionary to a list. Then to make them a json file I changed to a str. My problem is that there is no white line and indent in the file.

My expected json file is sth like

"[
    {
     'id': 1,
      'name': 'jasmin',
       'rel': []
     },
     {
      'id': 10,  
       'name': 'Dhoya',
        'rel': [
                  {'id':3,
                   'name': 'ana',
                   'rel':[
                           {
                             'id': 4, 
                              'name': 'ash', 
                               'rel': []
                            }
                          ]
                    }
                ]
        }
 ]"

I have tried replace "\n" but it would type '\n' instead of a new line.

2

There are 2 best solutions below

2
On

You could use json.dumps(your_dictionary, indent=2) to pretty print the json.

The json.dumps() method takes the python object and returns a JSON formatted string. The indent parameter is used to define the indent level for the formatted string.

Note: you'll require to import json

0
On

Have you tried to use dump() instead of dumps().

import json

data = []
rel = []

data.append({
    'id': '1',
    'name': 'jasmin',
    'rel': []
})

data.append({
'id': '10',
'name': 'Dhoya',
'rel': {'id': 3,
        'name': 'ana',
        'rel': {
                'id': 4,
                'name': 'ash',
                'rel': []
                }
        }
})


with open('data.json', 'w') as outfile:
    json.dump(data, outfile, indent=4)