从python中的文件加载json后检查密钥是否丢失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44145784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:45:30  来源:igfitidea点击:

Check if key is missing after loading json from file in python

pythonpython-3.x

提问by Philipp Klos

I'm getting the JSON via:

我通过以下方式获取 JSON:

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.

我想检查它是否data["example"]为空。

回答by Martin Peck

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

"example" in data.keys()将返回 True 或 False,因此这将是一种检查方法。

So, given JSON like this...

所以,鉴于这样的 JSON ......

  { "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:

以下代码将返回 True 或 False:

x = "example" in data   # x set to True
y = "cheese" in data    # y set to False

回答by elethan

You can try:

你可以试试:

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

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

即使密钥"example"不存在,这也不会引发错误。

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 KeyErrorwhich 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 Noneand will return the value otherwise. This is important to note because if you do a check like:

在您的情况下发生的是data["example"]不等于"",实际上没有键,"example"因此您可能会看到KeyError当您尝试使用不存在的键访问字典中的值时会发生什么。使用时.get("somekey"),如果键"somekey"不存在,get()将返回None,否则将返回值。这一点很重要,因为如果您进行以下检查:

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

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

这将通过 if 测试 if data["example"]is ""orif the key"example"不存在。

回答by user1620443

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