【问题标题】:How to convert Python List of numbers to json object如何将 Python 数字列表转换为 json 对象
【发布时间】:2020-08-21 23:20:36
【问题描述】:

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

input is a number like 22

期望的输出:

{
    "budget" : 22
} 

【问题讨论】:

  • 这不是有效的 JSON,因为 "budget" 键是重复的。
  • 如果我在列表中只有一个数字 .. like.. input x=[1], output = {"budget": 1}

标签: python json


【解决方案1】:

首先,“有效”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

【讨论】:

  • json 键像 \"budget\" : 1 而不是 "budget" : 1
  • @Rahul 这样“来”在哪里?
  • 在api调用返回的json中
  • 这可能是因为您正在使用某种形式的 Rest 框架,该框架第二次将其转换为 JSON。如果是这种情况,请尝试删除将python_dict 转换为json_obj 的最后一步。来源:stackoverflow.com/questions/28249491/…
  • 非常感谢你,对 python django 真的很陌生,它让我很难做一些小事
【解决方案2】:

您的示例不是有效的 JSON,因为您不能有重复的键。

你可以做的是有一些类似的东西:

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

可以这样实现:

import json

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

【讨论】:

  • 感谢瑞安。对不起,JSON 不能有重复的键
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2021-10-18
  • 1970-01-01
  • 2018-05-01
  • 2022-01-05
  • 1970-01-01
  • 2016-10-06
相关资源
最近更新 更多