mson mson - 4 months ago 9
JSON Question

Insert a value in json file with python

For a project, I need to use json for store some values :

{
"Serial_011": "011",
"Servers_011":
[
{
"hostname": "srv-a.11",
"ipv4_address": "0.0.0.0",
"services":
[
{
"uri": "http://www.google.fr/1",
"expected_code": 200
},
{
"uri": "http://www.google.fr/2",
"expected_code": 200
}
]
},
{
"hostname": "nsc-srv-b.11",
"ipv4_address": "0.0.0.0",
"services":
[
{
"uri": "http://www.google.fr/3",
"expected_code": 200
},
{
"uri": "http://www.google.fr/4",
"expected_code": 200
}
]
}
]
}


I want to add a service with this format :

{
"uri": "http://www.google.fr"
"expected_code": 200
}


So it will have this format :

{
"Serial_011": "011",
"Servers_011":
[
{
"hostname": "srv-a.11",
"ipv4_address": "0.0.0.0",
"services":
[
{
"uri": "http://www.google.fr/1",
"expected_code": 200
},
{
"uri": "http://www.google.fr/2",
"expected_code": 200
},
{
"uri": "http://www.google.fr"
"expected_code": 200
}
]
},
{
"hostname": "nsc-srv-b.11",
"ipv4_address": "0.0.0.0",
"services":
[
{
"uri": "http://www.google.fr/3",
"expected_code": 200
},
{
"uri": "http://www.google.fr/4",
"expected_code": 200
}
]
}
]
}


But I can not do this... I try with .append() but it's in local, json.dumps() but i can not go further than the first indent...

This is what I try with .append() :

with open('Example_of_configuration', 'r') as f:
dic = json.load(f)
dic['Servers_011'][0]['services'].append('{"uri":"http://www.google.com", "expected_code": 200}')


Somebody know how to do ?

Thanks in advance

Answer
with open('test.json', 'r') as f:
    dic = json.load(f)
    dic['Servers_011'][0]['services'].append({"uri": "http://www.google.com", "expected_code": 200})

with open('test.json', 'w') as f:
    json.dump(dic, f)
Comments