dikitin
dikitin

Reputation: 1

Getting AttributeError parsing JSON data

I'm getting a JSON data from server and I need to parse it separately, when I do this with SimpleNamespace I get the problem. How can I parse this data?

Example Data:

{
  "version":"1.0",
  "packageName":"com.some.thing",
  "eventTimeMillis":"1503349566168",
  "subscriptionNotification":
  {
    "version":"1.0",
    "notificationType":4,
    "purchaseToken":"PURCHASE_TOKEN",
    "subscriptionId":"my.sku"
  }
}

My Code:

import json
from types import SimpleNamespace

def callback(message):
    x = json.loads(message.data, object_hook=lambda d: SimpleNamespace(**d))
    
    print("Version: " + x.version)
    print("Package Name: " + x.packageName)
    print("Time Milis: " + x.eventTimeMillis)
    print("Token: " + x.subscriptionNotification.purchaseToken)
    print("Product: " + x.subscriptionNotification.subscriptionId)
    print("Type: " + str(x.subscriptionNotification.notificationType))

Error:

AttributeError: 'types.SimpleNamespace' object has no attribute 'subscriptionNotification'

Upvotes: 0

Views: 230

Answers (1)

user2668284
user2668284

Reputation:

In this example, we start with a dictionary. From then on there's very little code and the whole thing becomes "table driven". For example, if your dictionary structure changes such that you add a new key to the top level then you just need to make a corresponding change to the L1 table. Hopefully this will give you some ideas on how to proceed:

D = {
    "version": "1.0",
    "packageName": "com.some.thing",
    "eventTimeMillis": "1503349566168",
    "subscriptionNotification":
    {
        "version": "1.0",
        "notificationType": 4,
        "purchaseToken": "PURCHASE_TOKEN",
        "subscriptionId": "my.sku"
    }
}


def doPrint(d, L):
    if d:
        for _l in L:
            print(f'{_l[0]}: {d.get(_l[1], "n/a")}')


L1 = [['Version', 'version'],
    ['Package Name', 'packageName'],
    ['Time Millis', 'eventTimeMillis']
]
L2 = [['Token', 'purchaseToken'],
    ['Product', 'subscriptionId'],
    ['Type', 'notificationType']
]

doPrint(D, L1)
doPrint(D.get('subscriptionNotification', None), L2)

Upvotes: 1

Related Questions