简体   繁体   中英

How to convert Python List of numbers to json object

I want to convert python list of numbers to a json object. input:

input is a number like 22

Desired output:

{
    "budget" : 22
} 

First of all, you cannot have duplicate keys in a "valid" json object.

Your best bet would be to convert your list into a Python dict like so, and then convert it into a JSON object:

import json

my_list = [22, 30, 44, 55] # Your starting list

python_dict = {"budget": my_list}  # Python dict

json_obj = json.dumps(python_dict)  # Convert python dict to JSON obj

Your example is not valid JSON since you can't have duplicate keys.

What you could do instead is have something along the lines of:

{
    "budget": [22, 30, 44, 55]
}

This can be achieved as follows:

import json

json_object = json.dumps({"budget": my_list})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM