我有以下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的打印件。
答案 0 :(得分:0)
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
此代码位于烧瓶应用程序中。
return
一个字符串或响应对象。 这是一个可行的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
答案 1 :(得分:-1)
您应该从JSON对象中读取的方式应该是object[property_name]
。
例如object[a]
理想情况下会根据您的示例返回。