【问题标题】:Key-Value has the data with string value however value string as multiple data which needs to be changed键值具有字符串值的数据,但值字符串作为需要更改的多个数据
【发布时间】:2021-10-29 23:14:06
【问题描述】:

这是 AWS 备份还原元数据

我有以下键值对数据,其中值具有整个字符串,其中包含多个需要更改的数据,例如 falsetruetruefalse

NetworkInterfaces 键的字符串值具有多个键值对,我无法更改,因为它是一个完整的字符串。

'NetworkInterfaces': '[{
            "AssociatePublicIpAddress":false,
            "DeleteOnTermination":false,
            "Description":"Primary network interface",
            "DeviceIndex":0,
            "Groups":["sg-xyz"],
            "Ipv6AddressCount":0,
            "Ipv6Addresses":[],
            "NetworkInterfaceId":"eni-xyz",
            "PrivateIpAddress":"0.0.0.0",
            "PrivateIpAddresses":[{"Primary":false,"PrivateIpAddress":"0.0.0.0"}],
            "SecondaryPrivateIpAddressCount":0,
            "SubnetId":"subnet-xyz",
            "InterfaceType":"interface"
                    }]'

【问题讨论】:

    标签: python json amazon-web-services backup restore


    【解决方案1】:

    您最好的选择仍然是 json.loads() 将其转换为字典。 但是,上面的字符串不是有效的 json 格式,下面是 ...

    {"NetworkInterfaces": [{ "AssociatePublicIpAddress":false, "DeleteOnTermination":false, "Description":"Primary network interface", "DeviceIndex":0, "Groups":["sg-xyz"], "Ipv6AddressCount":0, "Ipv6Addresses":[], "NetworkInterfaceId":"eni-xyz", "PrivateIpAddress":"0.0.0.0", "PrivateIpAddresses":[{"Primary":false,"PrivateIpAddress":"0.0.0.0"}], "SecondaryPrivateIpAddressCount":0, "SubnetId":"subnet-xyz", "InterfaceType":"interface" }]}
    

    建议使用python re模块将字符串转换为类似的东西,以后可以被json模块使用

    添加示例代码以清理数据

    str = """
    'NetworkInterfaces':'[{"AssociatePublicIpAddress":false,"DeleteOnTermination":false,"Description":"Primary network interface","DeviceIndex":0,"Groups":["sg-xyz"],"Ipv6AddressCount":0,"Ipv6Addresses":[],"NetworkInterfaceId":"eni-xyz","PrivateIpAddress":"0.0.0.0","PrivateIpAddresses":[{"Primary":false,"PrivateIpAddress":"0.0.0.0"}],"SecondaryPrivateIpAddressCount":0,"SubnetId":"subnet-xyz","InterfaceType":"interface"}]'
    """
    
    
    import re
    str = re.sub('\'\[', '[', str)
    str = re.sub('\]\'', ']', str)
    str = re.sub('\'', '\"', str)
    str = re.sub('^\n', '', str)
    str = re.sub('\n$', '', str)
    str = "{" + str + "}"
    
    import json
    d = json.loads(str)
    print(d["NetworkInterfaces"][0]["AssociatePublicIpAddress"]) # False
    

    【讨论】:

    • 如您所说,我们如何使用 re 模块将字符串转换为有效的 json 格式?
    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多