user8853874
user8853874

Reputation:

how I can change some values of my json file?

I have a json file that is a list of dic. For an example the two elements of it are:

[{'key': 'chief information security officer',
  'top_transitions': [{'security architect': 5.0},
   {'cyber security manager': 3.0},
   {'information security officer': 3.0}]},
 {'key': 'security auditor',
  'top_transitions': [{'information security analyst': 9.0},
   {'information security officer': 9.0},
   {'it auditor': 6.0}]}]

I need to change some of the values of top_transitions by my hand.For an example how I can change {'security architect': 5.0} by {'student': 15.0}?

Upvotes: 0

Views: 33

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can use this example to change {"security architect": 5.0} to {"student": 15.0} (data is loaded from your Json file):

import json

to_search = {"security architect": 5.0}
to_replace = {"student": 15.0}

for item in data:
    if to_search in item["top_transitions"]:
        item["top_transitions"].remove(to_search)
        item["top_transitions"].append(to_replace)


print(json.dumps(data, indent=4))

Prints:

[
    {
        "key": "chief information security officer",
        "top_transitions": [
            {
                "cyber security manager": 3.0
            },
            {
                "information security officer": 3.0
            },
            {
                "student": 15.0
            }
        ]
    },
    {
        "key": "security auditor",
        "top_transitions": [
            {
                "information security analyst": 9.0
            },
            {
                "information security officer": 9.0
            },
            {
                "it auditor": 6.0
            }
        ]
    }
]

Upvotes: 1

Related Questions