1

Creating a json file using python which will have multiple entries as follows :

    out=''
    with open('data.json', 'w') as outfile:
        i=0;

        for i in range(3):
             string = "test_"+str(i)+'"'+':{ "status": "false", "test_id": 123453},'
             out= out+string.replace("\\","");
             i=i+1;      
        json.dump("{"+out+"}", outfile)

The file getting output as:

 "{test_0\":{ \"status\": \"false\", \"test_id\": 123453},test_1\":{ \"status\": \"false\", \"test_id\": 123453},test_2\":{ \"status\": \"false\", \"test_id\": 123453},}"

But ideally correct output should be as :

 {
 "test_0":
    {
     "status": "false", 
    "test_id": 123453
    },
  "test_1":
    { 
     "status": "false",
     "test_id": 123453
    },
  "test_2":
    { 
      "status": "false",
     "test_id": 123453
    }
}

So the output which is coming has "\" how do i remove them all. Its always appearing inside the file, have tried using strip too but not worth. Help!!

golu kashyap
  • 213
  • 2
  • 5
  • 10
  • 1
    Possible duplicate of [How to prettyprint a JSON file?](https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file) – fferri Apr 28 '18 at 21:09
  • 1
    If you want a JSON object, not a JSON string, then why are you passing a *string* to `json.dump` instead of the corresponding data python data type (a `dict`)? – juanpa.arrivillaga Apr 28 '18 at 21:15

2 Answers2

3

Do you try to re-make json.dump? Normally, json.dump do that work.

import json
import sys

out = {}
i = 0

for i in range(3):
    out["test_"+str(i)] = { "status": "false", "test_id": 123453 }
    i = i + 1

json.dump(out, sys.stdout, indent = 4)
set0gut1
  • 1,652
  • 1
  • 8
  • 21
0

The json module in build to dump pyhton data structure into suitable json code.

You provided it with a string - and it dumped it as it would be correct for a string. It masked each inner " by placing it as \" into your file so that when you read the file and json.load() it, it recreates the exact python string you gave it.

Bottom line: dont build strings of data, build the data and let json do its job:

import json
d =  {'test_0': {'status': 'false', 'test_id': 123453}, 
      'test_1': {'status': 'false', 'test_id': 123453}, 
      'test_2': {'status': 'false', 'test_id': 123453}}

with open('data.json', 'w') as outfile:
    json.dump(d,outfile, indent=4)   # use indent to pretty print


with open('data.json', 'r') as outfile:
    print("")
    print(outfile.read())

Output:

{
    "test_0": {
        "status": "false",
        "test_id": 123453
    },
    "test_1": {
        "status": "false",
        "test_id": 123453
    },
    "test_2": {
        "status": "false",
        "test_id": 123453
    }
}

Doku: https://docs.python.org/3/library/json.html

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69