从Python中的文本文件生成json文件并删除不必要的大括号

时间:2016-11-12 16:09:02

标签: python json loops

基本上我是从文本文件生成一个json Terraform文件,但是我无法以正确的方式进行格式化:

我希望完成的Terraform文件看起来像这样:

{
  "resource": {
    "aws_route53_record": {

      "analytics": {
        "name": "analytics",
        "records": ["1.2.3.4"],
        "ttl": "1800",
        "type": "A"
      },

      "analytics-test": {
        "name": "analytics-test",
        "records": ["1.2.3.4"],
        "ttl": "300",
        "type": "A"
      }
    }
  }
}

这是Terraform解析json所需的格式。

所以我在Python中加载文本文件,并遍历每一行,生成一个如下所示的列表列表:

records = [["analytics", "1.2.3.4", "1800", "A"],["analytics-test", "1.2.3.4", "300", "A"]]

我此刻生成文件的代码如下所示

我创建了一个包含顶级变量的dict占位符,如下所示:

json_object = {'resource': {'aws_route53_record': None}}

然后我浏览记录并分配适当的值:

for each_list in data:
    terrarecord = {
        each_list[0]:{
            "name": each_list[0],
            "type": each_list[2],
            "ttl": each_list[1],
            "records": [each_list[3].replace('\n', '')]
        }
    }

record_holder.append(terrarecord)

record_holder对象是一个空列表,然后我用它来填充json_objects,如下所示:

json_object['resource']['aws_route53_record'] = record_holder

这使我在完成的文件中得到的是:

    {
    "resource": {
        "aws_route53_record": [{
            "analytics": {
                "ttl": "1800",
                "records": ["173.194.245.129"],
                "name": "analytics",
                "type": "A"
            }
        }, {
            "analytics-test": {
                "ttl": "300",
                "records": ["130.211.89.168"],
                "name": "analytics-test",
                "type": "A"
            }
        }]
    }
}

那么,如果不添加我的小循环所需的额外[]{},会有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

为什么要在创建字典时创建中间列表?

terrarecord = {}
for each_list in data:
    terrarecord[each_list[0]] = {
        "name": each_list[0],
        "type": each_list[2],
        "ttl": each_list[1],
        "records": [each_list[3].replace('\n', '')]
    }
}

json_object['resource']['aws_route53_record'] = terrarecord