'Check if JSON dict property exists

I want to iterate through JSON output using Python and check if specific properties exist. These properties are "network_ip" and "port". If either one or both values do not exist, an error should be thrown.

I can access individual dictionary items using "item["destination"][0]" but, I am unsure how to loop through each dictionary item and check if the value exists.

Here is my code:

with open('temp.yaml') as f:
    data = yaml.load(f, Loader=SafeLoader)
    for item in data["network"]["info"]:
        print(item["destination"])  

Here is the resulting JSON:

{'network_ip': ['172.66.72.44/32'], 'port': [443]}
{'network_ip': ['172.33.48.33/32'], 'port': [1582]}
{'network_ip': ['172.22.24.3/32'], 'port': [443]}
{'network_ip': ['172.49.20.22/32'], 'port': [80]}
{'network_ip': ['172.43.24.153/32'], 'port': [1629]}
{'network_ip': ['172.43.48.34/32'], 'port': [443]}

Here is the structure of the original data:

network:
  info:
  - action: Allow
    protocol: TCP
    destination:
      network_ip:
      - 172.66.72.44/32 
      port:
      - 443
  - action: Allow
    protocol: TCP
    destination:
      nets:
      - 172.33.48.33/32
      port:
      - 1582    
  - action: Allow
    protocol: TCP
    destination:
      nets:
      - 172.22.24.3/32 
      port:
      - 443
  - action: Allow
    protocol: TCP
    destination:
      nets:
      - 172.49.20.22/32
      port:
      - 80
  - action: Allow
    protocol: TCP
    destination:
      nets:
      - 172.43.24.153/32 
      port:
      - 1629
  - action: Allow
    protocol: TCP
    destination:
      nets:
      - 172.43.48.34/32
      port:
      - 443


Solution 1:[1]

Assuming that the output shown is coming from item["destination"], you could try using in to check if both keys exist in the dictionary:

"network_ip" in item["destination"] and "port" in item["destination"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aaossa