首页 > 解决方案 > 将字典转换为保留双引号的文件

问题描述

我正在尝试将 adictionary转换为file需要传递给curl命令的 a 。当我使用它按预期写入的格式进行dictionary转储时,我需要更新其中的一些值。但是双引号被替换为单引号。有没有办法以精确的格式保留?以下是我的代码json.dumpstringdictionaryfile

接收输出

{
    'type': 'taskSap',
    'actions': {
        'abortActions': [],
        'emailNotifications': [{
            'attachFile': False,
            'attachStdError': False,
            'attachStdOut': False,
            'bcc': None,
            'body': None,
}

我正在使用的代码

with open("/sbranch/CTK/SAP/hkeep/vrpoutput.json", 'w') as file:
    json_string = json.dumps(mydict, default=lambda o: o.__dict__, sort_keys=True)
    file.write(json_string)

标签: python-3.x

解决方案


最初我从 api 调用收到的输出创建了字典。在字典中进行更改对我来说更容易。但是我改变了我的逻辑而不是字典,我已经将 api 的输出写入文件并使用正则表达式来更改我需要的字符串。

orig_string=""""type": "taskSap",
"actions": {
    "abortActions": [],
    "emailNotifications": [],
    "setVariableActions": [345erd],
    "snmpNotifications": [],
    "systemOperations": []
}"""

newstring='"All is good"'
ss = re.search(r"\"setVariableActions.*?,", orig_string)
if ss:
    pattern=(ss.group(0))
    #print(pattern)
result=orig_string.replace(pattern,newstring)
print(result)

推荐阅读