1

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.

2 Answers 2

1

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()

Sign up to request clarification or add additional context in comments.

2 Comments

That's pretty cool, but can we use list of keys instead of passing individual names, like instead of 'id', can we verify it with ['id', 'name', 'description']
@TaimoorPasha You can try if any(word in dct for dct in data for word in ["id", "name", "description"]): ...
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.