Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

json - How to print which key is "missing" and for which key i am getting "false" response from below script?

My Script

def validate_record_schema():
    """Validate that the 0 or more Payload dicts in record
    use proper types"""
    err_path = "root"
    try:
        for record in original_data:
            device = record["Device"]
            icon = device["Icon"]

            key_data = ((device["ManualAdded"], bool), (device["Location"], (str, type(None))),
                        (device["Version"], (str, type(None))), (device["Vendor"], (str, type(None))), (device["Language"], list),
                        (device["Fullname"], (str, type(None))),
                        (device["SchemaVersion"], (str, type(None))),(device["Warnings"], list),
                        (icon["DeviceType"], (str, type(None)))),(icon["Decorators"], (str, type(None))),
                       (device["SysSwUpdatePrepare"], (str, type(None))),(device["SysSwUpdatePerform"], (str, type(None)))
            for i in key_data:
                if not isinstance(*i):
                    return False

    except KeyError as err_path:
        print("missing key")
        return False
    return True

print(validate_record_schema())

I want to print which key is missing(If key is not presented) and for which key i am getting "false" as response.

Please modify my script according to that.

Json data

original_data =[{'Id': '12', 'Type': 'DevicePropertyChangedEvent', 'Payload': [{'DeviceType': 'producttype', 'DeviceId': 2, 'IsFast': False, 'Payload': {'DeviceInstanceId': 2, 'IsResetNeeded': False, 'ProductType': 'product'
    , 'Product': {'Family': 'home'}, 'Device': {'DeviceFirmwareUpdate': {'DeviceUpdateStatus': None, 'DeviceUpdateInProgress': None, 'DeviceUpdateProgress': None, 'LastDeviceUpdateId': None}, 'ManualAdded': False,
     'Name': {'Value': 'Jigital60asew', 'IsUnique': True}, 'State': None, 'Location': '', 'Serial': None, 'Version': '2.0.1.100','Vendor':'Sennheiser','Language':['en_GB']}}}]}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest going the route of using JSON Schema for validating your JSON instead of reinventing the wheel.

https://python-jsonschema.readthedocs.io/en/latest/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...