Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating Key in JSON File
#1
Hi all, this is my first post as I am a Python beginner and would greatly appreciate any help. Basically, I need to update a a JSON file used by a service that contains a simple JSON list. However, rather than the values I need to replace the key names so the roles map to an Active Directory group within the sample file below:

Output:
{ "operations": { "ops_modify": { "paths": [ "ops_set_config" ], "methods": [ "GET" ] }, "ops_read": { "paths": [ "ops_get_summary", "ops_get_request_info" ], "methods": [ "GET" ] } }, "roles": { "Server Op": [ "emc", "mgmt", "fips_read" ], "Deployer": [ "mgmt", "config" ], "KP Admin": [ "mgmt", "kp" ] }, "permissions": { "logs": [ "ops_read", "file" ], "adminusers": [ "adminusers.read" ] } }
So, I need to replace the 'Deployer' role with an AD distinguished name such as 'CN=Dev_Deployer,OU=test,DC=example,DC=com'. I've already updated another JSON file using the json module but in that case I only needed to change the values against a key, not the key itself. I have managed to achieve the above by using the code below:

def replace_acls(self, filename, dn, role):
    with open(filename, 'r') as f:
        dn = f.read().replace(role, dn)

    with open(filename, 'w') as f:
        f.write(dn)
However, I'd like to follow best practice of using the JSON module instead but cannot get it to write the data back to the file. As an example of the code I cannot get to work:

import json

with open('acl.json', 'r') as f:
    data = json.load(f)
    for item in data['roles']:
        item = item.replace('Deployer', 'CN=Dev_Deployer,OU=test,DC=example,DC=com')

with open('acl.json', 'w') as f:
    json.dump(data, f, indent=2)
Any ideas, thanks in advance?
Reply
#2
I added code to print out dictionary before and after changes, also cleaned up code a bit
** Note ** Uses f-string which requires python 3.6 or newer

import json
import os


def replace_acls(self, filename, dn, role):
    with open(filename, 'r') as f:
        dn = f.read().replace(role, dn)
 
    with open(filename, 'w') as f:
        f.write(dn)

def display_dict(dictname, level=0):
    '''
    Display formatted dictionary 
    '''
    indent = " " * (4 * level)
    for key, value in dictname.items():
        if isinstance(value, dict):
            print(f'\n{indent}{key}')
            level += 1
            display_dict(value, level)
        else:
            print(f'{indent}{key}: {value}')
        if level > 0:
            level -= 1

def main():
    # anchor starting directory
    os.chdir(os.path.abspath(os.path.dirname(__file__)))

    with open('acl.json', 'r') as f:
        data = json.load(f)
    
    print(f'\nDictionary before modification', end='')
    display_dict(data)

    data['roles']['Deployer'] = ['CN=Dev_Deployer','OU=test','DC=example','DC=com']

    print(f'\nDictionary after modification', end='')
    display_dict(data)

    with open('acl.json', 'w') as f:
        json.dump(data, f, indent=2)

if __name__ == '__main__':
    main()
Output:
Output:
Dictionary before modification operations ops_modify paths: ['ops_set_config'] methods: ['GET'] ops_read paths: ['ops_get_summary', 'ops_get_request_info'] methods: ['GET'] roles Server Op: ['emc', 'mgmt', 'fips_read'] Deployer: ['mgmt', 'config'] KP Admin: ['mgmt', 'kp'] permissions logs: ['ops_read', 'file'] adminusers: ['adminusers.read'] Dictionary after modification operations ops_modify paths: ['ops_set_config'] methods: ['GET'] ops_read paths: ['ops_get_summary', 'ops_get_request_info'] methods: ['GET'] roles Server Op: ['emc', 'mgmt', 'fips_read'] Deployer: ['CN=Dev_Deployer', 'OU=test', 'DC=example', 'DC=com'] KP Admin: ['mgmt', 'kp'] permissions logs: ['ops_read', 'file'] adminusers: ['adminusers.read']
Reply
#3
Hi Larz60+ thanks for your post, really appreciate the response. However, that's not quite what I was after as it actually needs to make the following changes to the file:

Output:
"roles" "Server Op" : ["emc", "mgmt", "fips_read"] "CN=Dev_Deployer,OU=test,DC=example,DC=com" : ["mgmt", "deploy", "config'] "KP Admin" : ["mgmt", "kp"]
So 'Deployer' itself changes to the distinguished name of 'CN=Dev_Deployer,OU=test,DC=example,DC=com'.
Reply
#4
You can't replace a key in a dictionary. You have to create a new entry in the dictionary with your new key, with the same contents as the old item. Then delete the old key/item if that's what is required.
Reply
#5
Thanks for confirming.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python openyxl not updating Excel file MrBean12 1 249 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  parse json field from csv file lebossejames 4 668 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Updating sharepoint excel file odd results cubangt 1 752 Nov-03-2023, 05:13 PM
Last Post: noisefloor
  Python Script to convert Json to CSV file chvsnarayana 8 2,343 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 1,959 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,161 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  validate large json file with millions of records in batches herobpv 3 1,221 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Writing to json file ebolisa 1 970 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Trying to parse only 3 key values from json file cubangt 8 3,336 Jul-16-2022, 02:05 PM
Last Post: deanhystad
  Initializing, reading and updating a large JSON file medatib531 0 1,722 Mar-10-2022, 07:58 PM
Last Post: medatib531

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020