1

I'm programming a python code in which I use JSONObjects to communicate with a Java application. My problem ist, that I want to change a value in the JSONObject (in this example called py_json) and the dimension of that JSONObject is not fixed but known. varName[x] is the input of the method and the length of varName is the dimension/size of the JSONObjects.

The code would work like that but I can't copy and paste the code 100 times to be sure that there are no bigger JSONObjects.

if length == 1:
   py_json[VarName[0]] = newValue
elif length == 2:
   py_json[VarName[0]][VarName[1]] = newValue
elif length == 3:
   py_json[VarName[0]][VarName[1]][VarName[2]] = newValue

In C I would solve it with pointers like that:

int *pointer = NULL;
pointer = &py_json;
for (i=0; i<length; i++){
   pointer = &(*pointer[VarName[i]]);
}
*pointer = varValue;

But there are no pointers in python. Do you known a way to have a dynamic solution in python?

MrH Punkt
  • 33
  • 3

1 Answers1

0

Python's "variables" are just names pointing to objects (instead of symbolic names for memory addresses as in C) and Python assignement doesn't "copies" a variable value to a new memory location, it only make the name points to a different object - so you don't need pointers to get the same result (you probably want to read this for more on python's names / variables).

IOW, the solution is basically the same: just use a for loop to get the desired target (actually: the parent of the desired target), then assign to it:

target = py_json
for i in range(0, length - 1):
    target = target[VarName[i]]

target[VarName[length - 1]] = newValue
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118