【问题标题】:If ... else .... ignored when checking Json attribute existanceIf ... else .... 检查 Json 属性是否存在时忽略
【发布时间】:2018-01-21 19:44:14
【问题描述】:

我有以下 Python3 代码来检查属性是否在 JSON 中(或具有不同于 null 的值)

def has_attribute(data, attribute):
    return (attribute in data) and (data[attribute] is not None)

这是检查属性是否在 JSON 中并且具有不同于 null 的值的函数。

if has_attribute(json_request,"offer_id"):
        print("IT IS")
else:
        print("NO")

问题是,当我传递 JSON 时,它不会打印任何内容。 为什么?

此代码位于烧瓶应用程序中。

我测试了这段代码通过 Postman 发送一个 json 对象(这是一个简单的 json 对象,如 {"a":"a","b":"b"})。
查询完成后,它会被接收,因为我看到了烧瓶接收到的 json,但没有打印来自 if..else 的打印。

【问题讨论】:

  • json_request 是什么类型的对象?这适用于字典
  • @cricket_007,它只是一个带有一些字符串属性的简单对象
  • 请显示问题的minimal reproducible example
  • 不是一个最小的、完整的和可验证的例子。但无论如何,我很困惑。 JSON 是一种基于文本的序列化格式。你在处理文本吗?或者,您是否正在处理从 JSON 文本反序列化的某个 Python 对象?在这种情况下,这个问题与 JSON 没有任何关系......顺便说一句,如果 data 实际上是 dict,那么您的函数可能只是 return data.get(attribute) is not None
  • @MarcBenedí 那么它是不是 JSON

标签: python json python-3.x


【解决方案1】:

JSON 不是 Python 中的一种类型。它可以是字符串,也可以是字典。

例如,您的代码在测试字典时可以正常工作

def has_attribute(data, attribute):
    return (attribute in data) and (data[attribute] is not None)

json_request = {'foo' : None, 'hello' : 'world'}

print("IT IS" if has_attribute(json_request, "foo") else "NO")  # NO
print("IT IS" if has_attribute(json_request, "bar") else "NO")  # NO
print("IT IS" if has_attribute(json_request, "hello") else "NO")  # IT IS

同样,如果您执行import json; json_request = json.loads(some_json_string),它也会起作用,因为这会返回一个字典。

如果您正在测试一个类,则需要使用 getattr() 内置函数重写它

class A:
  def __init__(self):
    self.x = None
    self.y = 'a'

  def has_attribute(self, attribute):
    return getattr(self, attribute, None) is not None

a = A()
print("IT IS" if a.has_attribute("foo") else "NO")  # NO
print("IT IS" if a.has_attribute("x") else "NO")  # NO
print("IT IS" if a.has_attribute("y") else "NO")  # IT IS

此代码位于烧瓶应用程序中。

  1. 打印语句最终出现在控制台/服务器日志中,而不是网页或 PostMan 中。您需要在 Flask 中 return 一个字符串或响应对象。
  2. How to get POSTed json in Flask?

这是一个可以运行的示例 Flask 应用程序。

from flask import Flask, request
app = Flask(__name__)

def has_attribute(data, attribute):
    return attribute in data and data[attribute] is not None

@app.route("/postit", methods=["POST"])
def postit():
    json_request = request.get_json()
    print(has_attribute(json_request, 'offer_id'))
    return str(has_attribute(json_request, 'offer_id'))

日志

 $ FLASK_APP=app.py python -m flask run
 * Serving Flask app "app"
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
False
127.0.0.1 - - [21/Jan/2018 14:19:10] "POST /postit HTTP/1.1" 200 -
True
127.0.0.1 - - [21/Jan/2018 14:19:25] "POST /postit HTTP/1.1" 200 -

请求与响应

$ curl -XPOST -H 'Content-Type:application/json' -d'{"offer_id":null}' http://localhost:5000/postit
False
$ curl -XPOST -H 'Content-Type:application/json' -d'{"offer_id":"data"}' http://localhost:5000/postit
True

【讨论】:

  • 我从 Flask 获取带有 request.get_json() 的 Json。 @app.route('/aaaaa',methods=['POST']) def request_bed(): bed_request = request.get_json()
  • 我已经更新了我的答案以包含工作 Flask 代码
【解决方案2】:

从 JSON 对象中读取的方式应该是 object[property_name]

例如,object[a] 理想情况下会根据您的示例返回一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2021-04-22
    • 2020-04-20
    • 2018-03-04
    • 1970-01-01
    相关资源
    最近更新 更多