Home > Mobile >  finding a specific object within duplicate element names, python with json
finding a specific object within duplicate element names, python with json

Time:12-01

I'm looking to grab the displayValue from objectAttributeValues where the objectTypeAttributeId = 14

there are multiple arrays like this, and the position of objectTypeAttributeId = 14 isn't always the same. how do I loop over every array to get that specific displayValue?

I've got something that looks through every possible array, but I want to clean it up.

sample json:

{
  "objectEntries": [{
      "attributes": [{
          "id": "5210",
          "objectAttributeValues": [{
            "displayValue": "10/Nov/22 3:33 PM",
            "referencedType": false,
            "searchValue": "2022-11-10T15:33:49.298Z",
            "value": "2022-11-10T15:33:49.298Z"
          }],
          "objectId": "1201",
          "objectTypeAttributeId": "12"
        },
        {
          "id": "5213",
          "objectAttributeValues": [{
            "displayValue": "02f9ed75-b416-49d0-8515-0601581158e5",
            "referencedType": false,
            "searchValue": "02f9ed75-b416-49d0-8515-0601581158e5",
            "value": "02f9ed75-b416-49d0-8515-0601581158e5"
          }],
          "objectId": "1201",
          "objectTypeAttributeId": "14"
        },
        {
          "id": "5212",
          "objectAttributeValues": [{
            "displayValue": "",
            "referencedType": false,
            "searchValue": "",
            "value": ""
          }],
          "objectId": "1201",
          "objectTypeAttributeId": "11"
        }
      ]
    },
    {
      "attributes": [{
          "id": "4263",
          "objectAttributeValues": [{
            "displayValue": "427904c5-e2c8-4735-bc38-4013928cd043",
            "referencedType": false,
            "searchValue": "427904c5-e2c8-4735-bc38-4013928cd043",
            "value": "427904c5-e2c8-4735-bc38-4013928cd043"
          }],
          "objectId": "1011",
          "objectTypeAttributeId": "14"
        },
        {
          "id": "4262",
          "objectAttributeValues": [{
            "displayValue": "",
            "referencedType": false,
            "searchValue": "",
            "value": ""
          }],
          "objectId": "1011",
          "objectTypeAttributeId": "11"
        }
      ]
    }
  ]
}

for this sample query, the values would be:

  • 02f9ed75-b416-49d0-8515-0601581158e5
  • 427904c5-e2c8-4735-bc38-4013928cd043

this is my code so far, and would like to make it for efficient:

from jira import JIRA
import requests
import json

base_url = "url"
auth = basic_auth=('user', 'pass')

headers = {
  "Accept": "application/json"
}

pages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


for page in pages:
    response = requests.request("GET",base_url   '?page='   str(page),headers=headers,auth=auth)
    all_output = json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))
    output_dict = json.loads(response.text)
    output_list = output_dict["objectEntries"]
    for outputs in output_list:
        print(outputs["attributes"][0]["objectId"])
        print(outputs["name"])
        print(outputs["objectKey"])
        if len(outputs["attributes"][0]["objectAttributeValues"][0]["displayValue"])==36:
            print(outputs["attributes"][0]["objectAttributeValues"][0]["displayValue"])
        if len(outputs["attributes"][1]["objectAttributeValues"][0]["displayValue"])==36:
            print(outputs["attributes"][1]["objectAttributeValues"][0]["displayValue"])
        if len(outputs["attributes"][2]["objectAttributeValues"][0]["displayValue"])==36:
            print(outputs["attributes"][2]["objectAttributeValues"][0]["displayValue"])
        if len(outputs["attributes"][3]["objectAttributeValues"][0]["displayValue"])==36:
            print(outputs["attributes"][3]["objectAttributeValues"][0]["displayValue"])
        if len(outputs["attributes"][4]["objectAttributeValues"][0]["displayValue"])==36:
            print(outputs["attributes"][4]["objectAttributeValues"][0]["displayValue"])
        print('\n')

Any suggestions would be appreciated!!

CodePudding user response:

You could browse your JSON dict and proceed each entries until you get the one(s) you are interested in.

# lets browse top level entries of your array
for e1 in outputs["objectEntries"]:
    # for each of those entries, browse the entries in the attribute section
    for e2 in e1["attributes"]:
        # does the entry match the rule "14"? If not, go to the next one
        if (e2["objectTypeAttributeId"] != 14):
            continue
        # print the current entry's associated value
        for attr in e2["objectAttributeValues"]
            print(attr["displayValue"])

CodePudding user response:

If structure is not changing then this can the solution It will iterate over all objects and add displayValue in search_values list

display_values = []
for object_entries in output_dict.get("objectEntries", []):
    for attribute in object_entries.get("attributes"):
        if attribute.get("objectTypeAttributeId") == "14":
            for object_attr in attribute.get("objectAttributeValues", []):
                if object_attr.get("displayValue") not in display_values:
                    display_values.append(object_attr.get("displayValue"))


print(display_values)

CodePudding user response:

You can iterate over your dict and check if the values matches with a function like this:

def get_display_value(my_dict, value):
    results = []
    for objectEntries in my_dict['objectEntries']:
        for attributes in objectEntries['attributes']:
            if int(attributes['objectTypeAttributeId']) == value:
                results.append(attributes['objectAttributeValues'][0]['displayValue'])
    return results

Using the function:

results = get_display_value(my_dict, 14)
print(results)

Outputs:

['02f9ed75-b416-49d0-8515-0601581158e5', '427904c5-e2c8-4735-bc38-4013928cd043']

Edit: now returning all match values instead of only the first one.

  • Related