我可以在Python中替换JSON键中的一部分字符串吗?

2024-10-03 19:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在这里的第一个问题,我对python还不熟悉,我正试图找出一些方法来建立一个自动的3D模型处理链,它依赖于存储在JSON文件中的数据从一个服务器移动到另一个服务器。在

问题是我需要将绝对路径存储到正在处理的文件,但是这些绝对路径应该在第一次处理时在原始JSON文件中进行修改。在

基本上JSON文件如下所示:

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

我想将文件路径重命名为

^{pr2}$

我一直在尝试使用以下代码替换路径的第一部分,但它不起作用:

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

但是这根本不起作用,所以我尝试正确解释JSON文件并替换来自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\\'
        settingsData.seek(0)  # 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

这很好地工作,但是我替换了整个路径,所以它不会真正适用于我需要处理的每个JSON文件。我真正想做的是获取一个与文件路径相对应的JSON密钥,保留最后8个字符,并用一个新的字符串替换补丁的其余部分,但我不知道如何在python中使用JSON来实现这一点,就我所知我不能编辑键的一部分。 有人对此有解决办法吗?在

谢谢!在


Tags: 文件the路径服务器jsonsettingscontentfile
3条回答

Python附带一个json库。 通过这个库,您可以读写JSON文件(或JSON字符串)。 解析的数据被转换成Python对象,反之亦然。在

要使用json库,只需导入它:

import json

假设您的数据存储在input_data.json文件中。在

^{pr2}$

你这样读文件:

import io

with io.open(input_data_path, mode="rb") as fd:
    obj = json.load(fd)

或者,或者:

with io.open(input_data_path, mode="rb") as fd:
    content = fd.read()
obj = json.loads(content)

您的数据会自动转换为Python对象,在这里您将得到一个dict

print(repr(obj))
# {u'projectdir': u'D:\\Outgoing\\1622_2\\',
#  u'normaldir': u'D:\\Outgoing\\1621_1\\'}

注意:我使用的是python2.7,所以您可以得到前缀为“u”的unicode字符串,比如u'projectdir'

现在很容易更改normaldirprojectdir的值:

obj["normaldir"] = "X:\\Incoming\\1621_1\\"
obj["projectdir"] = "X:\\Incoming\\1622_2\\"

由于objdict,您还可以使用update方法,如下所示:

obj.update({'normaldir': "X:\\Incoming\\1621_1\\",
            'projectdir': "X:\\Incoming\\1622_2\\"})

这样,您就可以使用类似JSON的语法。在

最后,您可以将Python对象写回JSON文件:

output_data_path = "output_data.json"

with io.open(output_data_path, mode="wb") as fd:
    json.dump(obj, fd)

或者,也可以使用缩进:

content = json.dumps(obj, indent=True)
with io.open(output_data_path, mode="wb") as fd:
    fd.write(content)

备注:使用缓冲区(变量content)读/写JSON对象更快。

替换逻辑失败,因为您需要将内容重新分配给新字符串,str.replace不是就地操作,它创建了一个新字符串:

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

使用json方法只需使用当前值进行替换:

^{pr2}$

如果您真的想保留最后8个字符并加上一个字符串,您还需要truncate()然后使用w重新打开文件并转储/写入新值:

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

.replace返回一个新字符串,不要更改它。但不应将json文件视为普通文本文件,因此可以将解析json与替换结合起来:

def processscan(scanfile):
    configfile= MonitorDirectory + scanfile
    with open(configfile, 'rb') as settingsData:
        settings = json.load(settingsData)

    settings = {k: v.replace("D:\\Outgoing\\", "X:\\Incoming\\")
        for k, v in settings.items()
    }

    with open(configfile, 'wb') as settingsData:
        json.dump(settings, settingsData)

相关问题 更多 >