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
此代码位于烧瓶应用程序中。
- 打印语句最终出现在控制台/服务器日志中,而不是网页或 PostMan 中。您需要在 Flask 中
return 一个字符串或响应对象。
- 见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