get name of "product" from json

Question:

this is JSON text, I want to get name of "product":

{"result": "success", "totalresults": 1, "startnumber": 0, "numreturned": 1, "orders": {"order": [{"id": 3267, "ordernum": 13424555, "userid": 2132, "contactid": 0, "requestor_id": 2173, "admin_requestor_id": 0, "date": "2022-08-05 16:39:18", "nameservers": "", "transfersecret": "", "renewals": "", "promocode": "", "promotype": "", "promovalue": "", "orderdata": "[]", "amount": "12.00", "paymentmethod": "usd", "invoiceid": 101, "status": "Active", "ipaddress": "111.111.111.111", "fraudmodule": "", "fraudoutput": "", "notes": "", "paymentmethodname": "Cryptocurrencies", "paymentstatus": "Paid", "name": "Max Vorenberg", "currencyprefix": "$", "currencysuffix": " USD", "frauddata": "", "validationdata": "", "lineitems": {"lineitem": [{"type": "product", "relid": 3648, "producttype": "Dedicated/VPS Server", "product": "Dedicated Server Windows", "domain": "chz", "billingcycle": "Monthly", "amount": "$12.00 USD", "status": "Active"}]}}]}}

this is my code:

     data = {
            'identifier':identifier,
            'secret':secret, 
            'action': 'GetOrders',
            'id':3267,
            'responsetype':'json',
            } 
    # sending post request and saving response as response object 
    r = requests.post(url = API_ENDPOINT, data = data) 
    data2 = r.json()
    text_data2 = json.dumps(data2)
    print(text_data2)
    print(text_data2['product'])

but get the error : "NameError: name 'string' is not defined"

Asked By: Philip

||

Answers:

dictionary_name: dict = {"Name": "John", "Age": 20, "City": "New York"}

print(f"{dictionary_name['Name']}")
print(f"{dictionary_name['Age']}")
print(f"{dictionary_name['City']}")

This will get you your expected result for your example input:

data["orders"]["order"][0]["lineitems"]["lineitem"][0]["product"]

Although, where I have [0] it is getting the first item in those lists. Your example has only one item in the lists but if there are more, you will need to iterate over them to get the result(s) you want.

This is based on your example data:

data = {
     'numreturned': 1,
     'orders': {'order': [{'admin_requestor_id': 0,
                           'amount': '12.00',
                           'contactid': 0,
                           'currencyprefix': '$',
                           'currencysuffix': ' USD',
                           'date': '2022-08-05 16:39:18',
                           'frauddata': '',
                           'fraudmodule': '',
                           'fraudoutput': '',
                           'id': 3267,
                           'invoiceid': 101,
                           'ipaddress': '111.111.111.111',
                           'lineitems': {'lineitem': [{'amount': '$12.00 USD',
                                                       'billingcycle': 'Monthly',
                                                       'domain': 'chz',
                                                       'product': 'Dedicated '
                                                                  'Server Windows',
                                                       'producttype': 'Dedicated/VPS '
                                                                      'Server',
                                                       'relid': 3648,
                                                       'status': 'Active',
                                                       'type': 'product'}]},
                           'name': 'Max Vorenberg',
                           'nameservers': '',
                           'notes': '',
                           'orderdata': '[]',
                           'ordernum': 13424555,
                           'paymentmethod': 'usd',
                           'paymentmethodname': 'Cryptocurrencies',
                           'paymentstatus': 'Paid',
                           'promocode': '',
                           'promotype': '',
                           'promovalue': '',
                           'renewals': '',
                           'requestor_id': 2173,
                           'status': 'Active',
                           'transfersecret': '',
                           'userid': 2132,
                           'validationdata': ''}]},
     'result': 'success',
     'startnumber': 0,
     'totalresults': 1
}

Explanation

To break this down I am first getting data["orders] which contains this dictionary:

{
 'order': [{'admin_requestor_id': 0,
            ...
            'lineitems': {'lineitem': [{'amount': '$12.00 USD',
                                        'billingcycle': 'Monthly',
                                        'domain': 'chz',
                                        'product': 'Dedicated Server Windows',
                                        'producttype': 'Dedicated/VPS Server',
                                        'relid': 3648,
                                        'status': 'Active',
                                        'type': 'product'}]},
            ...
    ]
}

This dictionary only has one key "orders", which contains a list containing a single dictionary. If you expect it to have more than one dictionary in it then you will need to loop through it like so:

for order in data["orders"]["order"]:
    ...

In the ... you would have a single order like the following:

{
     'admin_requestor_id': 0,
     ...
     'lineitems': {'lineitem': [{'amount': '$12.00 USD',
                                 'billingcycle': 'Monthly',
                                 'domain': 'chz',
                                 'product': 'Dedicated Server Windows',
                                 'producttype': 'Dedicated/VPS Server',
                                 'relid': 3648,
                                 'status': 'Active',
                                 'type': 'product'}]},
     ...
    }

This has a key "lineitems" which is a dictionary containing a single key "lineitem" which is another list of dictionaries and like above you can iterate this as well. Our code thus far would become:

for order in data["orders"]["order"]:
    for item in order["lineitems"]["lineitem"]:
        ...

Now in the inner loop we have a dictionary like the following:

{
    'amount': '$12.00 USD',
    'billingcycle': 'Monthly',
    'domain': 'chz',
    'product': 'Dedicated Server Windows',
    'producttype': 'Dedicated/VPS Server',
    'relid': 3648,
    'status': 'Active',
    'type': 'product'
}

This dictionary has the key "product" which is the value we are looking for. Our iterative approach now becomes:

for order in data["orders"]["order"]:
    for item in order["lineitems"]["lineitem"]:
        print(item["product"])
Answered By: Jab

It’s easier to see why, when the json is formatted visually:

{
    "result": "success",
    "totalresults": 1,
    "startnumber": 0,
    "numreturned": 1,
    "orders": {
        "order": [
            {
                "id": 3267,
                "ordernum": 13424555,
                "userid": 2132,
                "contactid": 0,
                "requestor_id": 2173,
                "admin_requestor_id": 0,
                "date": "2022-08-05 16:39:18",
                "nameservers": "",
                "transfersecret": "",
                "renewals": "",
                "promocode": "",
                "promotype": "",
                "promovalue": "",
                "orderdata": "[]",
                "amount": "12.00",
                "paymentmethod": "usd",
                "invoiceid": 101,
                "status": "Active",
                "ipaddress": "111.111.111.111",
                "fraudmodule": "",
                "fraudoutput": "",
                "notes": "",
                "paymentmethodname": "Cryptocurrencies",
                "paymentstatus": "Paid",
                "name": "Max Vorenberg",
                "currencyprefix": "$",
                "currencysuffix": " USD",
                "frauddata": "",
                "validationdata": "",
                "lineitems": {
                    "lineitem": [
                        {
                            "type": "product",
                            "relid": 3648,
                            "producttype": "Dedicated/VPS Server",
                            "product": "Dedicated Server Windows",
                            "domain": "chz",
                            "billingcycle": "Monthly",
                            "amount": "$12.00 USD",
                            "status": "Active"
                        }
                    ]
                }
            }
        ]
    }
}

The product value that you are looking for is nested under a collection of objects and arrays, so you’ll need a more sophisticated approach to parsing the value out.

At its simplest, you could access it via data2["orders"]["order"][0]["lineitems"]["lineitem"][0]["product"], but this assumes that all the objects and arrays are present, that they contain values, and the first item in each array is the one you want. Nothing to go wrong there. 😉

Also, you may want to add in some try blocks around the request etc, as if they fail they’ll throw an exception.

Answered By: Buffoonism
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.