Home > Mobile >  How do I return a nested json object with json.dumps()?
How do I return a nested json object with json.dumps()?

Time:02-23

I'm trying to figure out how to return a nested JSON object in Python.

I have a function that I am trying to mimic an HTTP server. The code so far is:

1. Function

def funcCustom(input_data: list):
    value = [100.23]
    return json.dumps({'stats': list(value)})

2. Make a call to function

my_input = [[19.0,1.0,0.0]]

predictCustom(my_input)

3. Current output:

'{"stats": [100.23]}'

My question is, how do I make my function return the following. If you notice, it is a nested JSON:

What I want it to output:

{
    "stats": {
        "val": 100.23,
        "isSet": true
    }
}

CodePudding user response:

You need to access the data and produce the desired data structure yourself. Simply with

def funcCustom(input_data: list):
    value = [100.23]
    return json.dumps({'stats': { 'val': value[0], 'isSet': True }})

That's all.

CodePudding user response:

Change return json.dumps({'stats': list(value)})

to

return json.dumps({"stats": {"val": value[0], "isSet": True}})
  • Related