Max Weaver Max Weaver - 20 days ago 10
Python Question

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:

I want the finished Terraform file to look like this:

{
"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.

So I load the text file in Python, and iterate over each line producing a list of lists that look like so:

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:

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:

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?

Answer

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
Comments