Home > Enterprise >  How to locate a value based on another value within the same key? Python & JSON
How to locate a value based on another value within the same key? Python & JSON

Time:04-20

I'm a new programmer and whilst I've searched for similar questions, I may need some direct help on this problem of mine. I have a data structure which is being returned in Python from an API I'm interacting with.

The data structure is like this:

{
  "account": "asdljasdjflallasjadsfkjlaasfd",
  "amount": [
    {
      "unit": "1019238741092834",
      "quantity": "1"
    },
    {
      "unit": "4893024890324830",
      "quantity": "2"
    },
    {
      "unit": "8374928483847485",
      "quantity": "3"
    },
    {
      "unit": "6574820387498457",
      "quantity": "4"
    }
  ],
  "subaccount": null,
  "type": "normal",
  "discrepancy": false
}

Is anyone able to tell me how to store the value "3" from "quantity": if all I know is "unit": "4893024890324830" which corresponds to it?

At the moment, I'm using json_object = json.loads(response.txt) and I can print and store values using json_object['amount'][1]['unit'] but that presumes I know the key/order of where the quantity I want is located within. The above is just a snippet, I have a large list including 1000 entries.

Thank you very much for your support in advance. First time using StackOverflow.

Cheers.

CodePudding user response:

If you know the unit value for e.g. "4893024890324830", then you can loop through the amount array and find the corresponding quantity using the unit value. Like this:

def storeQuanity(myval):
    for val in data["amount"]:
        if(val["unit"]==myval):
            print(val["quantity"])
storeQuanity("6574820387498457")
  • Related