我是 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/