0

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!!

1
  • not getting the desired results - a good question tells us what happened. I assume you got a syntax error, but don't make me guess! Commented Nov 2, 2016 at 1:46

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Note: You can give enumerate a starting number: enumerate(data['permutations'], 1). Saves you that index + 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.