6

I'm getting the JSON via:

with open("config.json") as data_file:
    global data
    data = json.load(data_file)

And I want to check if the data["example"] is empty or not.

4
  • 2
    Ok, what's your question? Have you tried anything? What's your sample data? Do you know how to get the length of a list? Commented May 23, 2017 at 22:05
  • Id like to check if the data["example"] existist in my json but when i try if data["example"] == "" it says a error Commented May 23, 2017 at 22:06
  • Your question is unclear. It's hard to know if you're trying to test for the existence of the key "example", or the presence of a value against that key. I've done my best with my answer, but you really should include ALL the info you can (including errors and surrounding code) Commented May 23, 2017 at 22:26
  • Hey @PhilippKlos. Fancy marking one of the answers as the correct answer? Commented Jul 5, 2017 at 20:40

3 Answers 3

8

"example" in data.keys() will return True or False, so this would be one way to check.

So, given JSON like this...

  { "example": { "title": "example title"}}

And given code to load the file like this...

import json

with open('example.json') as f:

    data = json.load(f)

The following code would return True or False:

x = "example" in data   # x set to True
y = "cheese" in data    # y set to False
Sign up to request clarification or add additional context in comments.

2 Comments

You don't even need the .keys(); in by default checks for the existence of keys in a dict.
good point. I was being a little more explicit, but less pythonic in doing so. I'll amend my answer
4

You can try:

if data.get("example") == "":
    ...

This will not raise an error, even if the key "example" doesn't exist.

What is happening in your case is that data["example"] does not equal "", and in fact there is no key "example" so you are probably seeing a KeyError which is what happens when you try to access a value in a dict using a key that does not exist. When you use .get("somekey"), if the key "somekey" does not exist, get() will return None and will return the value otherwise. This is important to note because if you do a check like:

if not data.get("example"): 
    ...

this will pass the if test if data["example"] is "" or if the key "example" does not exist.

Comments

1
if isinstance(data, dict) and "example" in data and data["example"] != "":
        # example exists and holds something

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.