Saffik
Saffik

Reputation: 1003

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

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
    }
}

Upvotes: 0

Views: 1179

Answers (2)

Shaida Muhammad
Shaida Muhammad

Reputation: 1650

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

to

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

Upvotes: 1

deets
deets

Reputation: 6395

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.

Upvotes: 1

Related Questions