2016-11-11 12 views
0

我有数据列表:环比多维列表,并创建一个从元素一个单独的JSON对象在Python

data = [['domain', '600', '10.0.0.1'],['domain2', '600', '10.0.0.2'],['domain3', '200', '10.0.0.3']] 

我想借此数据,并使用它来创建一个JSON一个terraform文件格式如下:

{ 
"resource": 
    { "aws_route53_record": { 
     "recordname": { 
       "zone_id": "", 
       "name": data[0][0], # --> takes 'domain' from the data list and inputs it here 
       "type": data[0][1], # --> takes '600' etc 
       "ttl": data[0][2] 
       # rest of code 
      } 

     } 

} 

我需要创建这些对象中的相当一部分,但字符串将保持每个相同。

参考,使更多的例子感,请参阅Terraform JSON语法指南here并通过创建一个Terraform记录route53引导可以发现here

一旦我已经创建了第一个JSON对象从列表中的第一个指标,我会再要移动到data[1][x]

我在Python的是非常初级的水平还是那么我希望这是足够的信息去

正如我测试试过这个:

for item in data: 
    print(item[0]) 

它打印:

['domain', '600', '10.0.0.1'] 
['domain2', '600', '10.0.0.2'] 

正如您所料。但是,在我失败的是,如果我做以下打印每个TTL值(指数1)

for item in data: 
    print(item[1]) 

它将打印TTL数字的列表中,但会拿出一个indexError: list item out of range

'600' 
'600' 
'200' 
Traceback (most recent call last): 
File "<stdin>", line 2, in <module> 
IndexError: list index out of range 

如果我尝试print(item[2])它错误马上。

,因为我得到这些indexErrors我卡在如何各项指标

+0

我加入了一些更多的信息,应该帮助 –

+0

是否'data'列表内的每个名单至​​少有3个项目? – yper

+0

这是一个非常好的问题。我正在处理一个非常大的文本文件,我将其转换为列表。我注意到并不是每个列表都有相同数量的项目。 –

回答

0

试图通过数据进行迭代,如果每个项目至少需要的元素的个数检查中访问正确的信息。

事情是这样的:

result = [] 
for item in data: 
    dict = { 
    "resource": 
     { "aws_route53_record": { 
      "recordname": { 
        "zone_id": "", 
        "name": item[0] if len(item) > 0 else "", # --> takes 'domain' from the data list and inputs it here 
        "type": item[1] if len(item) > 1 else "", # --> takes '600' etc 
        "ttl": item[2] if len(item) > 2 else "" 
        # rest of code 
       } 

      } 

    } 
    result.append(dict) 
+0

甚至更​​好,我已经整理了我的txt文件,所以每行都有相同的列数。现在完美工作,而无需添加任何额外的逻辑。 感谢您指引我在正确的方向。 –

相关问题