2017-10-18 85 views
1

我需要从解析的数据中创建一个输出json(预定义的格式),我得到一个字符串数据类型 - 我无法将其转换为所需的格式。从字符串对象列表中创建一个输出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输出,我不能够FIX-

{ 
    "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" 
     } 
    ] 
} 

回答

0

你只需要更正一行:

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