Skip to content
Advertisement

Path inside the dictionary from the variable

I have a code:

def replaceJSONFilesList(JSONFilePath, JSONsDataPath, newJSONData):
    JSONFileHandleOpen = open(JSONFilePath, 'r')
    ReadedJSONObjects = json.load(JSONFileHandleOpen)
    JSONFileHandleOpen.close()
    ReadedJSONObjectsModifyingSector = ReadedJSONObjects[JSONsDataPath]
    for newData in newJSONData:
        ReadedJSONObjectsModifyingSector.append(newData)
    JSONFileHandleWrite = open(JSONFilePath, 'w')
    json.dump(ReadedJSONObjects, JSONFileHandleWrite)
    JSONFileHandleWrite.close()

def modifyJSONFile(Path):
    JSONFilePath = '/path/file'
    JSONsDataPath = "['first']['second']"
    newJSONData = 'somedata'
    replaceJSONFilesList(JSONFilePath, JSONsDataPath, newJSONData)

Now I have an error:

KeyError: "['first']['second']"

But if I try:

ReadedJSONObjectsModifyingSector = ReadedJSONObjects['first']['second']

Everything is okay.

How I should send the path to the list from the JSON’s dictionary — from one function to other?

Advertisement

Answer

You cannot pass language syntax elements as if they were data strings. Similarly, you could not pass the string “2 > 1 and False”, and expect the function to be able to insert that into an if condition.

Instead, extract the data items and pass them as separate strings (which matches their syntax in the calling routine), or as a tuple of strings. For instance:

JSONsDataPath = ('first', 'second')
...

Then, inside the function …

ReadedJSONObjects[JSONsDataPath[0]][JSONsDataPath[1]]

If you have a variable sequence of indices, then you need to write code to handle that case; research that on Stack Overflow.

The iterative way to handle an unknown quantity of indices is like this:

obj = ReadedJSONObjects
for index in JSONsDataPath:
    obj = obj[index]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement