[英]Generating json file from text file in Python and removing unnecessary braces
Basically I'm generating a json Terraform file from a text file, but I can't get it to format in the correct way: 基本上,我是从文本文件生成json Terraform文件的,但是我无法以正确的方式格式化它:
I want the finished Terraform file to look like this: 我希望完成的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"
}
}
}
}
which is the format Terraform requires to parse json. 这是Terraform解析json所需的格式。
So I load the text file in Python, and iterate over each line producing a list of lists that look like so: 因此,我将文本文件加载到Python中,并在每一行上进行迭代,以生成如下所示的列表列表:
records = [["analytics", "1.2.3.4", "1800", "A"],["analytics-test", "1.2.3.4", "300", "A"]]
My code to generate the file at the moment looks like this 我目前用于生成文件的代码如下所示
I create a dict placeholder containing top level variable like so: 我创建一个包含顶级变量的dict占位符,如下所示:
json_object = {'resource': {'aws_route53_record': None}}
Then I look through records and assign the appropriate values: 然后,我浏览记录并分配适当的值:
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)
The record_holder
object is an empty list that I then use to fill in the json_objects
like so: record_holder
对象是一个空列表,然后我用它填充json_objects
如下所示:
json_object['resource']['aws_route53_record'] = record_holder
What this gives me in the finished file is: 这在完成的文件中给我的是:
{
"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"
}
}]
}
}
So would there be an easier way to do this without adding the extra []
and {}
s that my little loop does? 因此,有没有一种更简单的方法可以在不添加我的小循环执行的额外
[]
和{}
的情况下做到这一点?
Why are you creating the intermediate list when you want the dictionary? 为什么需要字典时要创建中间列表?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.