Alex Rebell
Alex Rebell

Reputation: 374

How do I replace the key in a JSON file?

Could you please tell me how can I replace the key in a JSON file?

JSON file structure:

[
   {
      "id" : "365",
      "credits" : [ {
        "login" : "user1",
        "password" : "pa$$w0rd"
      } ]
    }, {
      "id" : "366",
      "credits" : [ {
        "Login" : "user2",
        "password" : "pa$$w0rd"
      } ]
    }
]

it is necessary that the login key be of the same type, i.e. with one register throughout the document, all Login keys become login.

This is necessary for further analysis and downloading of information from the JSON file.

with open ("test.json", "r") as read_file_json:
    data_json = json.load(read_file_json)
    for n in range(len(data_json)):
        id = (data_json[n]['id'])
        id = str(id)
        for credits in data_json[n]["credits"]:
            login = credits["login"]

Thank you very much!

Upvotes: -1

Views: 242

Answers (1)

Adon Bilivit
Adon Bilivit

Reputation: 27000

There's no need to work with the id key. It serves no purpose. All you need is:

import json

with open ('test.json', encoding='utf-8') as read_file_json:
    js = json.load(read_file_json)
    for d in js:
        for c in d['credits']:
            if (v := c.get('Login', None)) is not None:
                c['login'] = v
                del c['Login']
    print(json.dumps(js, indent=2))

Upvotes: 1

Related Questions