如何使用python验证json数据格式和类型?

时间:2018-03-31 07:45:15

标签: python json python-3.x

json数据:

    [
       {
            "DeviceInstanceId": 5,
            "IsResetNeeded": null,
            "ProductType": "12345",
            "Product": {
                "Family": "12345"
            },
            "Device": {
                "DeviceFirmwareUpdate": {
                    "DeviceUpdateStatus": null,
                    "DeviceUpdateInProgress": null,
                    "DeviceUpdateProgress": null,
                    "LastDeviceUpdateId": null
                },
                "ManualAdded": {
                    "Value": false
                },
                "Location":{
                    "Value":"bangalore"
                }
         }
    ]

如何使用python验证上述json数据中是否存在“value”键。 如果上面的json数据中没有“value”键,那么我需要验证json数据格式应该如下所示

[
       {
            "DeviceInstanceId": 5,
            "IsResetNeeded": null,
            "ProductType": "12345",
            "Product": {
                "Family": "12345"
            },
            "Device": {
                "DeviceFirmwareUpdate": {
                    "DeviceUpdateStatus": null,
                    "DeviceUpdateInProgress": null,
                    "DeviceUpdateProgress": null,
                    "LastDeviceUpdateId": null
                },
                "ManualAdded": false,

                "Location":"bangalore"

         }
    ]

更新了json数据

[{
    "Id": "12",
    "Type": "DevicePropertyChangedEvent",
    "Payload": [{
        "DeviceType": "producttype",
        "DeviceId": 2,
        "IsFast": false,
        "Payload": {
            "DeviceInstanceId": 2,
            "IsResetNeeded": false,
            "ProductType": "product",
            "Product": {
                "Family": "home"
            },
            "Device": {
                "DeviceFirmwareUpdate": {
                    "DeviceUpdateStatus": null,
                    "DeviceUpdateInProgress": null,
                    "DeviceUpdateProgress": null,
                    "LastDeviceUpdateId": null
                },
                "ManualAdded": false,
                "Name": {
                    "Value": "Jigital60asew",
                    "IsUnique": true
                },
                "State": null,
                "Location": "bangalore",
                "Serial": null,
                "Version": "2.0.1.100"
            }
        }
    }]
}]

更新了json数据,请查看...对于更新的json,应该修改已接受的答案。请帮助

我该如何验证?

2 个答案:

答案 0 :(得分:0)

以下是要解决的两个问题。

  1. 遍历json中的所有元素
  2. 如果值包含密钥"Value"
  3. ,则更改元素值
    import json
    from collections import OrderedDict
    
    
    # solve first issue    
    def walk(node):
        for key, item in node.items():
            if isinstance(item, dict) and 'Value' in item:
                # I don't understand what is your 'verify' mean
                # I just change the value, you should 'verify' it here
                node[key] = change_if_value_exist(item)
            elif isinstance(item, dict):
                walk(item)
    
    
    # solve second issue   
    def change_if_value_exist(d):
        if isinstance(d, dict):
            if 'Value' in d:
                return d['Value']
        return d    
    
    if __name__ == '__main__':
        # json_txt is your input text 
        json_data = json.loads(json_txt, object_pairs_hook=OrderedDict)
        walk(json_data[0])
        new_json = json.dumps(json_data, indent=4)
        print(new_json)
    

答案 1 :(得分:0)

要验证记录是否采用其中一种格式,您可以执行以下操作:

代码:

def validate_record_schema(record):
    device = record.get('Device', {})
    manual_added = device.get('ManualAdded', None)
    location = device.get('Location', None)
    if isinstance(manual_added, dict) and isinstance(location, dict):
        if 'Value' in manual_added and 'Value' in location:
            return True
    return isinstance(manual_added, bool) and isinstance(location, str)

测试代码:

data = [
    {
        "DeviceInstanceId": 5,
        "IsResetNeeded": None,
        "ProductType": "12345",
        "Product": {
            "Family": "12345"
        },
        "Device": {
            "DeviceFirmwareUpdate": {
                "DeviceUpdateStatus": None,
                "DeviceUpdateInProgress": None,
                "DeviceUpdateProgress": None,
                "LastDeviceUpdateId": None
            },
            "ManualAdded": {
                "Value": False
            },
            "Location": {
                "Value": "bangalore"
            }
        }
    },
    {
        "DeviceInstanceId": 5,
        "IsResetNeeded": None,
        "ProductType": "12345",
        "Product": {
            "Family": "12345"
        },
        "Device": {
            "DeviceFirmwareUpdate": {
                "DeviceUpdateStatus": None,
                "DeviceUpdateInProgress": None,
                "DeviceUpdateProgress": None,
                "LastDeviceUpdateId": None
            },
            "ManualAdded": False,
            "Location": "bangalore"
        }
    },
    {
        "DeviceInstanceId": 5,
        "IsResetNeeded": None,
        "ProductType": "12345",
        "Product": {
            "Family": "12345"
        },
        "Device": {
            "DeviceFirmwareUpdate": {
                "DeviceUpdateStatus": None,
                "DeviceUpdateInProgress": None,
                "DeviceUpdateProgress": None,
                "LastDeviceUpdateId": None
            },
            "ManualAdded": {
            },
            "Location": {
                "Value": "bangalore"
            }
        }
    },
    {
        "DeviceInstanceId": 5,
        "IsResetNeeded": None,
        "ProductType": "12345",
        "Product": {
            "Family": "12345"
        },
        "Device": {
            "DeviceFirmwareUpdate": {
                "DeviceUpdateStatus": None,
                "DeviceUpdateInProgress": None,
                "DeviceUpdateProgress": None,
                "LastDeviceUpdateId": None
            },
            "ManualAdded": 0,
            "Location": "bangalore"
        }
    }
]



print([validate_record_schema(r) for r in data])

结果:

[True, True, False, False]