Home > Software engineering >  Verify all keys within JSON Array using Python request
Verify all keys within JSON Array using Python request

Time:08-10

I have JSON Array like this:

   data = """ [
        {
            "id": 1,
            "name": "crm/index",
            "description": "CRM/Dashboard"
        },
        {
            "id": 2,
            "name": "crm/index/with_search",
            "description": "CRM/Global Search"
        }
    ]"""

Now, I have to verify that within this json three keys i.e. 'id', 'name' and 'description' are displaying throughout.

I have used following method:

student = json.loads(data)
if "id" in student:
   print("Key exist in JSON data")
else:
   print("Key doesn't exist in JSON data")

But it is returning me else statment, I need to know, where I am making mistake.

CodePudding user response:

You probably want any():

import json

data = """\
[
    {
        "id": 1,
        "name": "crm/index",
        "description": "CRM/Dashboard"
    },
    {
        "id": 2,
        "name": "crm/index/with_search",
        "description": "CRM/Global Search"
    }
]"""

data = json.loads(data)

if any("id" in dct for dct in data):
    print("Key exists in data")
else:
    print("Key doesn't exists in data")

Prints:

Key exists in data

If you want to check if key id exists in all dictionaries in data, use all() instead of any()

CodePudding user response:

Try this

import json


data = """ [
    {
        "id": 1,
        "name": "crm/index",
        "description": "CRM/Dashboard"
    },
    {
        "id": 2,
        "name": "crm/index/with_search",
        "description": "CRM/Global Search"
    }
]"""
students = json.loads(data)
for student in students:
    if "id" in student:
        print("Key exist in JSON data")
    else:
        print("Key doesn't exist in JSON data")
  • Related