从字符串对象列表创建输出json文件

时间:2017-10-18 10:19:13

标签: python json python-2.7 python-3.x

我需要从解析后的数据中创建输出json(预定义格式),这是我在字符串数据类型中获取的 - 我无法将其转换为所需的格式。

import json
name = 'Dojo'
version = '1.1.1'
author = 'Alice'
# For next execution of for loop there will be new values for each variable mentioned above
sample = {'name': name,  'version': version, 'author':author}
d = {"id":"12345",
"Assets":[{'name':value,"version":value,"author":value} for key,value in sample.items()]}     
j = json.dumps(d, indent=4)
print (j)

我需要以下面的格式创建一个输出json文件 -

{
  "id" :"12345",
  "Assets" : [{
    "name" : "Dojo",
    "version" : "1.1.1",
    "author" : "Alice",  
  },{
    "name" : "Gogo",
    "version" : "1.2.3",
    "author" : "Bob", 
  }],
}  

我上面的代码创建了一个我无法修复的json输出 -

{
    "id": "12345",
    "Assets": [
        {
            "version": "1.1.1",
            "name": "1.1.1",
            "author": "1.1.1"
        },
        {
            "version": "Dojo",
            "name": "Dojo",
            "author": "Dojo"
        },
        {
            "version": "Alice",
            "name": "Alice",
            "author": "Alice"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

您只需更正一行:

d = {"id":"12345",
"Assets":[{key:value for key,value in sample.items()}]}