Parse JSON starting with bracket in python

Viewed 89

I have a .json file structured as well:

"[{\"dataset\": \"x0\", \"test\": \"Test 3 \", \"results\": {\"TP\": 0, \"FP\": 0, \"FN\": 0, \"TN\": 17536}, \"dir\": \"/Users//Test_3\"}]"

When I try to read it with the following code:

with open(dir, 'r+') as f:
   data = json.load(f)
print(data[0])

I get [ as output, which means it is reading the json object as a string. I do not understand if the problem is how I'm saving it. Since I populate it in a loop, the code which creates this object is the following one:

json_obj = []
for i in range(len(dictionary)):
    dataset, test, dir = retrieve_data()
    tp, fp, tn, fn = calculate_score()
    json_obj.append({'dataset': dataset,
                            'test': test,
                            'results': {'TP': tp, 'FP': fp, 'FN': fn, 'TN': tn},
                            'dir': dir })
json_dump = json.dumps(json_obj)
with open(save_folder, 'w') as outfile:
        json.dump(json_dump, outfile)

The structure I tried to create is the following one:

{
 "dataset": "1",
 "test": "trial1",
 "results": {
     "TP": 5,
     "FP": 3,
     "FN": 2,
     "TN": 5
  },
 "dir": dir
}

How can I read it correctly to make it parsable?

1 Answers

You are converting json_obj to a string and then dumping the string to a file. Dump json_obj directly to the file:

#json_dump = json.dumps(json_obj)
with open(save_folder, 'w') as outfile:
        json.dump(json_obj, outfile)
Related