简体   繁体   English

如何将 Python 数字列表转换为 json object

[英]How to convert Python List of numbers to json object

I want to convert python list of numbers to a json object.我想将 python 数字列表转换为 json object。 input:输入:

input is a number like 22

Desired output:所需的 output:

{
    "budget" : 22
} 

First of all, you cannot have duplicate keys in a "valid" json object.首先,“有效” 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:您最好的选择是将您的列表转换为 Python 字典,然后将其转换为 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.您的示例无效 JSON 因为您不能有重复的密钥。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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