5

This is the script

def validate_record_schema(record):
        device = record.get('Payload', {})
        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 False
        return isinstance(manual_added, bool) and isinstance(location, str)

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

This is json data

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": null,
                        "DeviceUpdateInProgress": null,
                        "DeviceUpdateProgress": null,
                        "LastDeviceUpdateId": null
                    },
                    "ManualAdded": {
                    "value":false
                    },
                    "Name": {
                        "Value": "Jigital60asew",
                        "IsUnique": true
                    },
                    "State": null,
                    "Location": {
                    "value":"bangalore"
                   },
                    "Serial": null,
                    "Version": "2.0.1.100"
                }
            }
        }]
    }]

For the line device = device.get('ManualAdded', None), I am getting the following error: AttributeError: 'list' object has no attribute 'get'.

please have a look and help me to solve this issue

Where i am doing mistake...

How can i fix this error?

Please help me to solve this issue

4
  • Looking at the data structure, "Payload": [...] Its a list of dicts. Commented Apr 1, 2018 at 6:23
  • 1
    @tdelaney How can i fix this issue?Please help me Commented Apr 1, 2018 at 6:26
  • 1
    You already have an answer to the problem.... I'm just adding the why. Its a list so you need to process the items in the list. You could get the first element as suggested below or put the whole thing in a for loop to process all of the dicts. Commented Apr 1, 2018 at 6:31
  • I am new to python...can u modify my function ?please...I don't know what to do Commented Apr 1, 2018 at 6:34

2 Answers 2

3

As the error suggests, you can't .get() on a list. To get the Location and ManualAdded field, you could use:

manual_added = record.get('Payload')[0].get('Payload').get('Device').get('ManualAdded')
location = record.get('Payload')[0].get('Payload').get('Device').get('Location')

So your function would become:

def validate_record_schema(record):
    manual_added = record.get('Payload')[0].get('Payload').get('Device').get('ManualAdded')
    location = record.get('Payload')[0].get('Payload').get('Device').get('Location')

    if isinstance(manual_added, dict) and isinstance(location, dict):
        if 'Value' in manual_added and 'Value' in location:
        return False
    return isinstance(manual_added, bool) and isinstance(location, str)

Note that this would set location to

{
    "value":"bangalore"
}

and manual_added to

{
    "value":false
}
Sign up to request clarification or add additional context in comments.

5 Comments

Can you modify in the same function please
I have expanded the answer, including context in your function.
Thanks for your valuable help...I was stuck from two days...Thank u so much
Now I get 'str' object has no attribute 'get'
@AnonymousUser I would suggest creating a new question with more details
3

You are having problems tracking types as you traverse data. One trick is to add prints along the way for debug to see what is going on. For instance, that top "Payload" object is a list of dict, not a single dict. The list implies that you can have more than one device descriptor so I wrote a sample that checks all of them and returns False if it finds something wrong along the way. you will likely need to update this according to your validation rules, but this will get you started.

def validate_record_schema(record):
    """Validate that the 0 or more Payload dicts in record
    use proper types"""
    err_path = "root"
    try:
        for device in record.get('Payload', []):
            payload = device.get('Payload', None)
            if payload is None:
                # its okay to have device without payload?
                continue
            device = payload["Device"]
            if not isinstance(device["ManualAdded"]["value"], bool):
                return False
            if not isinstance(device["Location"]["value"], str):
                return False
    except KeyError as e:
        print("missing key")
        return False

    return True

1 Comment

Thanks for your great help...I was stuck from two days...Thank u so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.