I am trying to insert parent object in the json but it inserts it on the top but I want to insert after particular key present in the json. I tried adding below code but it insert parent at the top (I understand since it is parent it will be inserted on the top but i want to insert before particular key in this case key is "pattern" :
with open ("myfile.json", 'r') as f:
myjson = json.load(f)
myjson = {'Main Parent': myjson}
Basically I want to insert "versions": before "pattern"
"versions":{
"pattern": {
"provider": "abc",
"schema": "xyz"
},
"baseline":{
"version" : "dev"
}
}
Input json file
{
"target": {
"Name": "abc",
"Occupation": "xyz"
},
"properties":{
"env" : "dev"
},
"use_it": "xyz",
"pattern": {
"provider": "abc",
"schema": "xyz"
},
"baseline":{
"version" : "dev"
}
}
Expected output json file
Input json file
{
"target": {
"Name": "abc",
"Occupation": "xyz"
},
"properties":{
"env" : "dev"
},
"use_it": "xyz",
"versions":{
"pattern": {
"provider": "abc",
"schema": "xyz"
},
"baseline":{
"version" : "dev"
}
}
}
2
Answers
Would something like this work for you?
The
pop
method deletes a key from a dict and returns its value.We store that value and place it back under the new "versions" key.
Output:
yes,you can dynamically get the keys from the
versions
dictionary and insert them before the "pattern" key in your JSON!check this out too:
as you see,the
versions
dictionary is defined with the desired key-value pairs,and during the iteration through the originalJSON
, when thepattern
key is encountered, theversions
dictionary is inserted before it!