Stephan Sturges Stephan Sturges - 1 year ago 62
JSON Question

Can I replace part of a string in a JSON key in Python?

This is my first question here, I'm new to python and trying to figure some things out to set up an automatic 3D model processing chain that relies on data being stored in JSON files moving from one server to another.

The problem is that I need to store absolute paths to files that are being processed, but these absolute paths should be modified in the original JSON files upon the first time that they are processed.

Basically the JSON file comes in like this:

"normaldir": "D:\\Outgoing\\1621_1\\",
"projectdir": "D:\\Outgoing\\1622_2\\"

And I would like to rename the file paths to

"normaldir": "X:\\Incoming\\1621_1\\",
"projectdir": "X:\\Incoming\\1622_2\\",

What I've been trying to do is replace the first part of the path using this code, but it isn't working:

def processscan(scanfile):
configfile= MonitorDirectory + scanfile
with open(configfile, 'r+') as file:
content =
content.replace("D:\\Outgoing\\", "X:\\Incoming\\")

However this was not working at all, so I tried interpreting the JSON file properly and replacing the key code from here:

def processscan(scanfile):
configfile= MonitorDirectory + scanfile
with open(configfile, 'r+') as settingsData:
settings = json.load(settingsData)
settings['normaldir'] = 'X:\\Incoming\\1621_1\\'
settings['projectdir'] = 'X:\\Incoming\\1622_2\\' # rewind to beginning of file
settingsData.write(json.dumps(settings,indent=2,sort_keys=True)) #write the updated version
settingsData.truncate() #truncate the remainder of the data in the file

This works perfectly, however I'm replacing the whole path so it won't really work for every JSON file that I need to process. What I would really like to do is to take a JSON key corresponding to a file path, keep the last 8 characters and replace the rest of the patch with a new string, but I can't figure out how to do this using json in python, as far as I can tell I can't edit part of a key.
Does anyone have a workaround for this?


Answer Source

Your replace logic failed as you need to reassign content to the new string,str.replace is not an inplace operation, it creates a new string:

 content =  content.replace("D:\\Outgoing\\", "X:\\Incoming\\")

Using the json approach just do a replace too, using the current value:

settings['normaldir'] =  settings['normaldir'].replace("D:\\Outgoing\\", "X:\\Incoming\\")

You also would want truncate() before you write or just reopen the file with w and dump/write the new value, if you really wanted to just keep the last 8 chars and prepend a string:

settings['normaldir'] =  "X:\\Incoming\\" + settings['normaldir'][-8:]