首页 > 解决方案 > 如何将 Python 数字列表转换为 json 对象

问题描述

我想将 python 数字列表转换为 json 对象。输入:

input is a number like 22

期望的输出:

{
    "budget" : 22
} 

标签: pythonjson

解决方案


首先,“有效”json 对象中不能有重复的键。

您最好的选择是将您的列表转换为 Python 字典,然后将其转换为 JSON 对象:

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

推荐阅读