python

时间:2017-04-24 18:26:32

标签: python json

我正在尝试使用python中的Dictionary创建一个json对象。据我所知,关键部分需要是唯一的,但在我的情况下,数组有多个具有相同键的项目,所以看起来字典在这里对我不起作用。试着在这里理解我的选择?最后,我将把这个json对象保存到服务器上的json文件中。

data = {}
data['key1'] = hostname

for line in pipe.stdout:
    parts = line.split() # split line into parts
    if len(parts) > 1:   # if at least 2 parts/columns
        data['package'] = { 'name': parts[0], 'installed': parts[1], 'available': parts[2]}

print(json.dumps(data, indent=4))

预期的Json输出

{

 "key1": "xyz-abc-m001",
 "package": [
   { "name":"abc", "installed":"1:1", "available":"1:1.2." },
   { "name":"xyz", "installed":"2.02", "available":"2.02" },
   { "name":"zyc", "installed":"1.17.1", "available":"1.17.1" }

 ]

}

1 个答案:

答案 0 :(得分:1)

data = {}
data['key1'] = hostname
data['package'] = []

for line in pipe.stdout:
    parts = line.split() # split line into parts
    if len(parts) > 1:   # if at least 2 parts/columns
        data['package'].append({ 'name': parts[0], 'installed': parts[1], 'available': parts[2]})