我是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"
}
]
}
答案 0 :(得分:4)
如果没有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使用无序映射。
答案 1 :(得分:2)
from pprint import pprint
result = {}
result['versionInformation'] = []
for val in las.version:
version_info = {}
version_info['mnemonic'] = val.mnemonic
version_info['unit'] = val.unit
version_info['value'] = val.value
version_info['description'] = val.descr
result['versionInformation'].append(version_info)
pprint(result)