Home > Mobile >  Create a json object and add items in a loop - python
Create a json object and add items in a loop - python

Time:10-13

I would like to create a JSON object structured as well:

{
     "dataset": "xx",
     "test": "trial",
     "results": {
         "TP": 5,
         "FP": 1,
         "FN": 1,
         "TN": 2
     }
 }

I calculate these results in a loop on this way:

json_obj = {}
for i in range(len(dictionary)):
    dataset, test = retrieve_data()
    tp, fp, tn, fn = calculate_score()
    json_obj = json.dumps({'dataset': dataset,
                            'test': test,
                            'results': {'TP': tp, 'FP': fp, 'FN': fn, 'TN': tn}})

Since I loop 4 times, I would expect a JSON object like this one:

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

     "dataset": "2",
     "test": "trial2",
     "results": {
         "TP": 6,
         "FP": 4,
         "FN": 12,
         "TN": 25
     },

     "dataset": "3",
     "test": "trial3",
     "results": {
         "TP": 15,
         "FP": 1,
         "FN": 11,
         "TN": 2
     },

     "dataset": "4",
     "test": "trial4",
     "results": {
         "TP": 5,
         "FP": 11,
         "FN": 1,
         "TN": 21
     }
 }

Where if I access to the first element with the commands:

json_obj = json.dumps(json_obj)
print (json_obj[0])

I get

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

The problem is that if I run the code I just get " as output. if I print the full json_obj I get the string:

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

It looks like it is creating a string instead of json object. Where is the error?

CodePudding user response:

when you call json_obj = json.dumps(somthingOrOther) you are creating a new object and overwriting the one from the previous iteration. So I would expect the output string from your code to be:

{"dataset": "dataSet-4", "test": 3, "results": {"TP": 9, "FP": 10, "FN": 7, "TN": 10}}

Note: I'm using random values for the results. I don't know how to add elements to a json object but you can work around it. Just write all your data to a list and than convert it to a json object using json.dumps. Which would look somthing like this.

import random, json

def calculate_score():
    return random.randint(0,10), random.randint(0,10),random.randint(0,10),random.randint(0,10)

json_obj_list = []
for i in range(5):
    tp, fp, tn, fn = calculate_score()
    json_obj_list .append({'dataset': f"dataSet-{i}",
                            'test': 3, #some random int
                            'results': {'TP': tp, 'FP': fp, 'FN': fn, 'TN': tn}})


json_dump = json.dumps(json_obj_list, indent="\t")
print(json_dump)

this prints the following

[
    {
        "dataset": "dataSet-0",
        "test": 3,
        "results": {
            "TP": 9,
            "FP": 10,
            "FN": 1,
            "TN": 4
        }
    },
    {
        "dataset": "dataSet-1",
        "test": 3,
        "results": {
            "TP": 2,
            "FP": 7,
            "FN": 5,
            "TN": 2
        }
    },
    {
        "dataset": "dataSet-2",
        "test": 3,
        "results": {
            "TP": 3,
            "FP": 8,
            "FN": 5,
            "TN": 8
        }
    },
    {
        "dataset": "dataSet-3",
        "test": 3,
        "results": {
            "TP": 3,
            "FP": 5,
            "FN": 8,
            "TN": 8
        }
    },
    {
        "dataset": "dataSet-4",
        "test": 3,
        "results": {
            "TP": 3,
            "FP": 1,
            "FN": 6,
            "TN": 5
        }
    }
]
  • Related