合并python列表并返回json

2024-09-24 22:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个python列表:

cols = ['InfoKey', 'InfoData']

以及

vals = ['Row 1: [LANGUAGE SUPPORT MODE, Standard]', 'Row 2: [RELEASE, 15.00.04.01]', 'Row 3: [VERSION, 15.00.04.01]']

如何合并它们并返回JSON类型:

{
"data": [{
        "Infokey": "LANGUAGE SUPPORT MODE",
        "InfoData": "Standard"
    },
    {
        "Infokey": "RELEASE",
        "InfoData": "15.00 .04 .01"
    },
    {
        "Infokey": "VERSION",
        "InfoData": "15.00 .04 .01"
    }
]

}


Tags: json类型support列表releasemodeversionlanguage
3条回答

您可以在这里使用regex来提取[...]之间的字符串。下面是示例

>>> import re
>>> vals = ['Row 1: [LANGUAGE SUPPORT MODE, Standard]', 'Row 2: [RELEASE, 15.00.04.01]', 'Row 3: [VERSION, 15.00.04.01]']
>>> for s in vals:
...     a, b = re.findall('\[([^"]*)\]', s)[0].split(', ')
...     print('Infokey: ', a)
...     print('InfoData: ', b)
...
Infokey:  LANGUAGE SUPPORT MODE
InfoData:  Standard
Infokey:  RELEASE
InfoData:  15.00.04.01
Infokey:  VERSION
InfoData:  15.00.04.01

PS:您需要将我在控制台上打印的输出存储到dict,并将每个dict对象附加到列表中。我把它留给你去做。

这个呢:

import json
l = []
for v in vals:
    info = v.split(': ')[1].replace('[', '').replace(']', '')
    key, data = info.split(', ')
    d = {}
    d["InfoKey"] = key
    d["InfoData"] = data
    l.append(d)

json_dict = {"data": l}

print json.dumps(json_dict)

结果:

{"data": [{"InfoData": "Standard", "InfoKey": "LANGUAGE SUPPORT MODE"}, {"InfoData": "15.00.04.01", "InfoKey": "RELEASE"}, {"InfoData": "15.00.04.01", "InfoKey": "VERSION"}]}

正如@PM所说,这在很大程度上取决于所描述的数据格式。你知道吗

import json

cols = ['InfoKey', 'InfoData']
vals = [
    'Row 1: [LANGUAGE SUPPORT MODE, Standard]',
    'Row 2: [RELEASE, 15.00.04.01]',
    'Row 3: [VERSION, 15.00.04.01]'
]

master = []

for item in vals:
    data = item[item.find('[')+1:item.find(']')]
    parts = data.split(',')
    master.append({cols[0]: parts[0].strip(),
        cols[1]: parts[1].strip()})

print json.dumps({'data': master})

相关问题 更多 >