deep deep - 1 month ago 9
JSON Question

Inserting new json dictionary object in json file

I have a dictionary which looks like below:

{

"permutations": [

{
"testname": "test1",
"file_type": "text",
"app_parent_folder": "folder",
"expected_result": "block"
},
{
"testname": "test2",
"file_type": "text",
"app_parent_folder": "folder",
"expected_result": "block"
}
]
}


I want to add a new object "rule_id": (no. of test cases) such that the json looks like below after the modification

{

"permutations": [
{
"testname": "test1",
"file_type": "text",
"app_parent_folder": "folder",
"expected_result": "block",
"rule_id": "1"
},
{
"testname": "test2",
"file_type": "text",
"app_parent_folder": "folder",
"expected_result": "block",
"rule_id": "2"
}
]
}


I tried using the below code but not getting the desired results

import json
from pprint import pprint

with open('example.json') as data_file:
data = json.load(data_file)

for rule_id_num in range(1,2):
data["permutations"].append('rule_id':rule_id_num)
pprint(data)


Please can someone help me regarding how can I add the dictionary in the above json file. Thank you in advance!!

Answer

Since the containers you're adding the rule_id to are dictionaries, you can't append to them. You have to add the value by key.

Try this:

import json
from pprint import pprint

with open('example.json') as data_file:
    data = json.load(data_file)

for index, d in enumerate(data['permutations'], 1):
    d['rule_id'] = str(index)

pprint(data)

One thing I have to ask, is there some relation between the testname and the rule_id?

Comments