Bhavya Patel
Bhavya Patel

Reputation: 27

JSON ID extraction from Array in Python

I wrote a script to pull data from Verizon's connectivity management API with the following. Below is the section that requests the line information based on the search item, in this case, the SIM or iccid. I did not include the previous parts because they are just to connect to the API and get credentials.

header = {
    'accept': 'application/json',
    'VZ-M2M-Token': session_token,
    'Authorization': 'Bearer' + bearer_token,
    'Content-Type': 'application/json',
}

data = '{ "deviceId": { "id": ' + SIM +', "kind": "ICCID" }}'

response = requests.post('https://thingspace.verizon.com/api/m2m/v1/devices/actions/list', headers=header, data=data)

And the response I get is a JSON Array which looks like

{
  "hasMoreData": false,
  "devices": [
    {
      "accountName": "123456789-00001",
      "billingCycleEndDate": "2020-10-31T20:00:00-04:00",
      "carrierInformations": [
        {
          "carrierName": "Verizon Wireless",
          "servicePlan": "3rrrrx48wwwwrjgjtyjtyjtyjtyj",
          "state": "active"
        }
      ],
      "connected": true,
      "createdAt": "2016-11-04T11:06:28-04:00",
      "deviceIds": [
        {
          "id": "5256694405",
          "kind": "mdn"
        },
        {
          "id": "3114949302094150",
          "kind": "imsi"
        },
        {
          "id": "35922505468230",
          "kind": "imei"
        },
        {
          "id": "891480000054957290575",
          "kind": "iccId"
        },
        {
          "id": "15256694405",
          "kind": "msisdn"
        },
        {
          "id": "5256694405",
          "kind": "min"
        }
      ],
      "extendedAttributes": [
        {
          "key": "PrimaryPlaceOfUseTitle"
        },
        {
          "key": "PrimaryPlaceOfUseFirstName",
          "value": "5256694405",
        },
        {
          "key": "PrimaryPlaceOfUseMiddleName"
        },
        {
          "key": "PrimaryPlaceOfUseLastName",
          "value": "ESN"
        },
        {
          "key": "PrimaryPlaceOfUseSuffix"
        },
        {
          "key": "PrimaryPlaceOfUseAddressLine1"
        },
        {
          "key": "PrimaryPlaceOfUseAddressLine2"
        },
        {
          "key": "PrimaryPlaceOfUseCity"
        },
        {
          "key": "PrimaryPlaceOfUseState"
        },
        {
          "key": "PrimaryPlaceOfUseCountry"
        },
        {
          "key": "PrimaryPlaceOfUseZipCode"
        },
        {
          "key": "PrimaryPlaceOfUseZipCode4"
        },
        {
          "key": "PrimaryPlaceOfUseCBRPhone"
        },
        {
          "key": "PrimaryPlaceOfUseCBRPhoneType"
        },
        {
          "key": "PrimaryPlaceOfUseEmailAddress"
        },
        {
          "key": "AccountNumber",
          "value": "5256694405-00001"
        },
        {
          "key": "SmsrOid"
        },
        {
          "key": "ProfileStatus"
        },
        {
          "key": "PromoCodes",
          "value": ""
        },
        {
          "key": "PromotionStartDate",
          "value": ""
        },
        {
          "key": "PromotionScheduledEndDate",
          "value": ""
        },
        {
          "key": "LeadId",
          "value": ""
        },
        {
          "key": "CustomerName",
          "value": ""
        },
        {
          "key": "CustomerAddressLine1",
          "value": ""
        },
        {
          "key": "CustomerAddressLine2",
          "value": ""
        },
        {
          "key": "CustomerAddressCity",
          "value": ""
        },
        {
          "key": "CustomerAddressState",
          "value": ""
        },
        {
          "key": "CustomerAddressZipCode",
          "value": ""
        },
        {
          "key": "ServiceZipCode",
          "value": ""
        },
        {
          "key": "SkuNumber",
          "value": "VZW080000460053"
        },
        {
          "key": "CostCenterCode"
        },
        {
          "key": "PreIMEI",
          "value": "3592254564568445"
        },
        {
          "key": "PreSKU",
          "value": "VZW080000100037"
        },
        {
          "key": "SIMOTADate",
          "value": "4/30/2020 1:22:18 PM"
        },
        {
          "key": "RoamingStatus",
          "value": "NotRoaming"
        },
        {
          "key": "LastRoamingStatusUpdate",
          "value": "9/24/2020 5:40:26 PM"
        }
      ],
      "groupNames": [
        "Default: 0220433754-00001"
      ],
      "ipAddress": "100.100.100.100",
      "lastActivationBy": "User Verizon",
      "lastActivationDate": "2016-11-04T11:06:28-04:00",
      "lastConnectionDate": "2020-09-24T13:40:26-04:00"
    }
  ]
}

I added a part to my script to pull the mdn, iccid and the imei from the array with the code that is below.

def puller(line_json):
  line_data = json.loads(line_json)
  mdn = (line_data['devices'][0]['deviceIds'][0]['id'])
  iccid = (line_data['devices'][0]['deviceIds'][3]['id'])
  imei = (line_data['devices'][0]['deviceIds'][2]['id'])

  print('phone = ' ,mdn)
  print('SIM = ' , iccid)
  print('IMEI = ' , imei)

I tested this code and it works the way it should with one test ID. I then proceeded to test with another test ID and I learned that the array structure is not always the same. That second JSON array is below. I am wondering is there a better way to find the specific values that I want, but in the way that I am not specifically telling the script where in the structure the item will be as I did above.

{
  "hasMoreData": false,
  "devices": [
    {
      "accountName": "02234234234-00001",
      "billingCycleEndDate": "2020-10-31T20:00:00-04:00",
      "carrierInformations": [
        {
          "carrierName": "Verizon Wireless",
          "servicePlan": "37776xdsfewsfwe576193",      
          "state": "active"
        }
      ],
      "connected": true,
      "createdAt": "2016-05-24T15:55:06-04:00",
      "deviceIds": [
        {
          "id": "0945437676404",
          "kind": "esn"
        },
        {
          "id": "1234565799",
          "kind": "mdn"
        },
        {
          "id": "31148454545458767",
          "kind": "imsi"
        },
        {
          "id": "01426786678211",
          "kind": "imei"
        },
        {
          "id": "89148000006456456454",
          "kind": "iccId"
        },
        {
          "id": "1234565799",
          "kind": "min"
        }
      ],
      "extendedAttributes": [
        {
          "key": "PrimaryPlaceOfUseTitle"
        },
        {
          "key": "PrimaryPlaceOfUseFirstName",
          "value": "096114564506772"
        },
        {
          "key": "PrimaryPlaceOfUseMiddleName"
        },
        {
          "key": "PrimaryPlaceOfUseLastName",
          "value": "096546454806772"
        },
        {
          "key": "PrimaryPlaceOfUseSuffix"
        },
        {
          "key": "PrimaryPlaceOfUseAddressLine1"
        },
        {
          "key": "PrimaryPlaceOfUseAddressLine2"
        },
        {
          "key": "PrimaryPlaceOfUseCity"
        },
        {
          "key": "PrimaryPlaceOfUseState"
        },
        {
          "key": "PrimaryPlaceOfUseCountry"
        },
        {
          "key": "PrimaryPlaceOfUseZipCode"
        },
        {
          "key": "PrimaryPlaceOfUseZipCode4"
        },
        {
          "key": "PrimaryPlaceOfUseCBRPhone"
        },
        {
          "key": "PrimaryPlaceOfUseCBRPhoneType"
        },
        {
          "key": "PrimaryPlaceOfUseEmailAddress"
        },
        {
          "key": "AccountNumber",
          "value": "02242342354-00001"
        },
        {
          "key": "SmsrOid"
        },
        {
          "key": "ProfileStatus"
        },
        {
          "key": "PromoCodes",
          "value": ""
        },
        {
          "key": "PromotionStartDate",
          "value": ""
        },
        {
          "key": "PromotionScheduledEndDate",
          "value": ""
        },
        {
          "key": "LeadId",
          "value": ""
        },
        {
          "key": "CustomerName",
          "value": ""
        },
        {
          "key": "CustomerAddressLine1",
          "value": ""
        },
        {
          "key": "CustomerAddressLine2",
          "value": ""
        },
        {
          "key": "CustomerAddressCity",
          "value": ""
        },
        {
          "key": "CustomerAddressState",
          "value": ""
        },
        {
          "key": "CustomerAddressZipCode",
          "value": ""
        },
        {
          "key": "ServiceZipCode",
          "value": ""
        },
        {
          "key": "SkuNumber",
          "value": "VZW12000364343005"
        },
        {
          "key": "CostCenterCode"
        },
        {
          "key": "PreIMEI"
        },
        {
          "key": "PreSKU",
          "value": "VZW12000334340005"
        },
        {
          "key": "SIMOTADate",
          "value": "3/13/2020 10:52:07 AM"
        },
        {
          "key": "RoamingStatus",
          "value": "NotRoaming"
        },
        {
          "key": "LastRoamingStatusUpdate",
          "value": "10/20/2020 6:14:20 PM"
        }
      ],
      "groupNames": [
        "Default: 02342343754-00001"
      ],
      "ipAddress": "101.101.101.101",
      "lastActivationBy": "User Verizon",
      "lastActivationDate": "2016-05-24T15:55:16-04:00",
      "lastConnectionDate": "2020-10-20T14:14:20-04:00"
    }
  ]
}

I tried to use this block of code from some research I did to find the value that I was looking for; in this case, the mdn. Problem I have is that the response returns a blank set of brackets with no information, so I know there is something I probably did wrong.

def json_extract(obj, kind):
    """Recursively fetch values from nested JSON."""
    arr = []

    def extract(obj, arr, kind):
        """Recursively search for values of key in JSON tree."""
        if isinstance(obj, dict):
            for k, v in obj.items():
                if isinstance(v, (dict, list)):
                    extract(v, arr, kind)
                elif k == kind:
                    arr.append(v)
        elif isinstance(obj, list):
            for item in obj:
                extract(item, arr, kind)
        return arr

    values = extract(obj, arr, kind)
    return values


names = json_extract(response , 'mdn')
print(names)

Upvotes: 0

Views: 110

Answers (1)

tsamridh86
tsamridh86

Reputation: 1496

I understood that you are trying to find, mdn, iccid and imei'id from the json object above,so, instead of recursion and the complicated coding that you have done there, it is easier to use python's inbuilt libraries to help you out:

You can use the next function for your purpose:

# load your json data
line_data = json.loads(data) 

# narrow your focus on the array in question
device_ids = line_data['devices'][0]['deviceIds']

# This gets the first item's id attribute from the list that matches the condition, and returns None if no item matches.

mdn = next((x['id'] for x in device_ids if x['kind'] == "mdn"), None)
iccid = next((x['id'] for x in device_ids if x['kind'] == "iccid"), None)
imei = next((x['id'] for x in device_ids if x['kind'] == "imei"), None)

You will need to handle the None if it was unable to find such element in the array.

Reference : Find object in list that has attribute equal to some value (that meets any condition)

Upvotes: 1

Related Questions