python - 将对象列表转换为 Json 数组

标签 python json

我是 python 的新手,我有一个这样的对象列表。

示例代码

>>> for val in las.version:
...     print(val.mnemonic)
...     print(val.unit)
...     print(val.value)
...     print(val.descr)
...
VERS

1.2
some description
WRAP

NO
another description
>>>

我想将其转换为 JSON 数组。

{  
   "versionInformation":[  
      {  
         "mnemonic":"VERS",
         "unit":"",
         "value":"2.0",
         "description":"some description"
      },
      {  
         "mnemonic":"WRAP",
         "unit":"",
         "value":"NO",
         "description":"another description"
      }
   ]
}

最佳答案

如果没有 HeaderItem 描述,这将无法解释可能的错误,但您可以使用 dict/list 组合轻松地重新创建 JSON 结构,然后使用内置的 json 模块来获取您想要的 JSON,即:

import json

version_info = [{"mnemonic": v.mnemonic, "unit": v.unit,
                 "value": v.value, "description": v.descr}
                for v in las.version]
print(json.dumps({"versionInformation": version_info}, indent=3))

请记住,在 CPython 3.6 和 Python 3.7 之前,通常无法保证各个版本信息的 JSON 中的项目顺序。如果这很重要,您可以改用 collections.OrderedDict - 它不应该,因为规范中的 JSON 使用无序映射。

关于python - 将对象列表转换为 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50000536/

相关文章:

python - 根据Python中给定的字符串对列表进行排序

arrays - R将data.frame转换为json

sql-server - OPENJSON 在 SQL Server 中不起作用?

json - 从流分析 -> 服务中心 -> 逻辑应用程序中解析逻辑应用程序中的 Json

python - 使用工作层在 Elastic Beanstalk 上使用 Django 设置计划/cron 作业

python - Flask-HTTPAuth verify_password

python - 无法连接到基于postgres的容器

python - 使用 Django Rest Framework 订购带有排序查询参数的detail_route

c# - Web 请求内容类型总是 text/html

javascript - Ajax 请求/响应 : how to make them lightning fast?