Is there a way to modify a JSON dictionary at different levels?

Can you assist me with updating the value of a dictionary key in a JSON file using variable keys?

Here's what currently works and the problem I'm encountering.

For example:

print(my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'])

This returns 'Mike'. Now, if I do this:

my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'] = 'Carol'

And execute the same print statement:

print(my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'])

The output is 'Carol', which is expected behavior.

However, my challenge arises when I don't know the specific index keys or their hierarchy. Although I can access a list of them, there are instances where I need to update values at different levels within the JSON structure.

my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username']

Other times, it may be located elsewhere in the JSON:

my_json['convergedSystem']['credentials'][0]['credentialElements']['username']

Or even at a deeper level like:

my_json['FullSystem'][switches]['endpoints'][2]['credentials'][0]['credentialElements']['username']

How can I dynamically set these values in code? I will always have access to a list containing the path to the desired key, but the specifics may vary.

['convergedSystem', 'endpoints', 0, 'credentials', 0, 'credentialElements', 'username']

Regardless, I'll consistently be targeting ['credentialElements']['username']. Thank you for your help!

Answer №1

Suppose you have a JSON object named my_json and an array called keys. You want to update the value to your_updated_value:

val = my_json  # storing reference to the json object
for key in keys[0:-1]:  # iterating until the second last level
    val = val[key]
val[keys[-1]] = your_updated_value  # updating the value

It's important to note that as val holds a reference to my_json, any changes made will also reflect back on my_json.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

rearranging elements in a tuple using Python

Is there a way to automatically switch the positions of elements within a tuple? For example, if I have a tuple ('a', 'b') and want it to be changed to ('b', 'a'). While I know this can be achieved by creating a new ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

Python - incorrect number of arguments provided for f.write: expected 1 argument, but received

import os from os import stat from pwd import getpwuid searchFolder = raw_input("Please input the directory you want to search (e.g. /Users/bubble/Desktop/): ") resultsTxtLocation = raw_input("FIBS will save the results in a txt file. Where should we save ...

"Embarking on a journey with Jackson and the power

There have been numerous questions regarding the use of Jackson for serializing/deserializing Java objects using the builder pattern. Despite this, I am unable to understand why the following code is not functioning correctly. The Jackson version being use ...

Ways to eliminate duplicates while retaining rows with a specific non-null value in another column using Pandas

My database contains multiple duplicate records, some of which have bank accounts. I am looking to retain only the records with a bank account. Essentially, something along the lines of: if there are two Tommy Joes: keep the one with a bank account ...

Strange screeching noise emanating from buzzer in Node.js

Lately, I've been experimenting with Node.js, dash buttons, and Raspberry Pi GPIO. I'm fairly new to working with GPIO, so I decided to tinker around with it. I have a buzzer connected to a breadboard that I activated using Python in the followin ...

Combine and update JSON files by matching ID's in PHP

I am facing an issue with merging JSON files in PHP. I want to overwrite data when the id's match, but it's not working as expected. Here is my PHP code: foreach($instagram_array['data'] as $key => $image){ $id = $image['id ...

When attempting to ajax post JSON data, I received a null response as well

I have attempted numerous times to implement the code below, but I keep receiving a null value. var cartViewModel = []; $(":text").each(function (i) { var quantity = parseInt($(this).val()); var id = parseInt($(this).data ...

Python: Parsing a file to identify duplicate strings

My current project involves creating an arithmetic game that presents the user with 10 random questions using numbers 1 to 10. The user's name and score out of 10 are then saved in a file named class_a.txt in this format: Student_Name,7 Another_Perso ...

What could be causing my pygame screen to become unresponsive when awaiting user input?

I have recently started learning Python programming and am working on developing a game for my class project. However, whenever I run the program, the screen becomes unresponsive before allowing the user to input anything. Can anyone help me figure out wha ...

There are no profile details available on Tensorboard at the moment

Issue There seems to be a problem with the profile section in Tensorboard. After running tensorboard --logdir logdir, I am unable to see anything on the Tensorboard interface. https://i.stack.imgur.com/SZrff.png The directory structure of logdir is as f ...

Struggling with parsing specific values in JSON file while trying to improve Python skills

Embarking on my first Python project focusing on Stardew Valley and its crop prices has been an exciting challenge. For those familiar with the game, you may know that each shop sells unique items, creating a diverse market. I am currently working with a ...

Filtering Strings with Prefix Matching in Python using Regular Expressions

When it comes to Regular Expressions, things can get a bit tricky. For example, I recently delved into a kernel on Kaggle for the Titanic dataset. In this dataset, there is a field containing the names of passengers. #Exploring the data and looking for r ...

Issue encountered while attempting to import vincent library into Python 3

Can someone help me figure out why I am having trouble importing vincent? https://i.stack.imgur.com/X3Jrj.png ...

A guide on enabling the second selection to fill data based on the chosen option from the

Whenever I make a selection in the first dropdown, the second dropdown should dynamically update based on that option. However, although the data is successfully populated in the first dropdown, the second dropdown still does not respond. I suspect that th ...

Specification for Application Input: Receiving input information for a specific method

Is there a recommended method for visually representing the input data structure required for a server application? I am working on specifying the correct input data that the server will receive via an http post request. The data being sent is a complex js ...

Before I open a new browser window, I receive an error message saying "Element not found

When trying to interact with the element labeled as "mat-select-arrow-wrapper.ng-tns-c73-7" on the provided website, I encounter an error stating that the element cannot be located. Strangely, this issue is resolved after clicking the new browser window on ...

Using Selenium in Python to retrieve a specific child element by referencing its parent

I am struggling to locate a specific subelement within a list of parent elements, encountering an issue where the full xpath works but breaking it down into parent => child does not yield the correct location (resulting in an error message). Here are t ...

Strange JSON format detected when consuming the Python Hug REST API in a .NET environment

When using a Hug REST endpoint to consume JSON in .net, there are issues with embedded characters that I am facing. See the example below for a complete failure. Any assistance would be greatly appreciated. Python @hug.post('/test') def test(re ...

What is the best way to utilize Python to solve and visualize a particular mathematical equation?

Hello, I am new to Python and have two questions that I hope you can help me solve. 1) How would I go about plotting all the points (x, y) that satisfy the following equation? y==11+(1+2x)((11x)/(5+10x))^((3y)/(3y-(5+x))) Given x>0 and y>0. 2) Now, let ...