我有一个基本的词典如下:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
Run Code Online (Sandbox Code Playgroud)
当我尝试做的时候,jsonify(sample)我得到:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
我能做些什么,以便我的字典样本可以克服上述错误?
注意:虽然它可能不相关,但字典是从mongodb中检索记录生成的,当我打印输出时str(sample['somedate']),输出是2012-08-08 21:46:24.862000.
我不确定我是否理解该flask.jsonify方法的目的.我尝试从这里创建一个JSON字符串:
data = {"id": str(album.id), "title": album.title}
Run Code Online (Sandbox Code Playgroud)
但我得到的东西与我所得到的json.dumps不同flask.jsonify.
json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business"}]
flask.jsonify(data): {"id":…, "title":…}
Run Code Online (Sandbox Code Playgroud)
显然我需要得到一个看起来更像json.dumps返回的结果.我究竟做错了什么?
我想在我的 Flask 网站(API 网站)上输出一个漂亮的 JSON,但我的 JSON 文件不想正确格式化。
我尝试了多种方法:
return json.loads(json.dumps(json_text, indent=4))
return json.dumps(json_text, indent=4)
return jsonify(json_text)
Run Code Online (Sandbox Code Playgroud)
json_it() 函数:
def json_it(self):
input_part = {"amount": self.amount, "currency": str(self.input_currency)}
output_part = self.result
return {"input": input_part, "output": output_part}
Run Code Online (Sandbox Code Playgroud)
烧瓶API代码:
converter = CurrencyConvert(float(amount), input_currency, output_currency)
json_text = converter.json_it()
the_output = json.dumps(json_text, indent=10)
print(the_output)
return the_output, 200
Run Code Online (Sandbox Code Playgroud)
CurrencyConvert 正在使用这 3 个参数,并根据它制作字典,正如您在打印它的输出中看到的那样。(那个应该不是问题)
输出(API):如果我打印它:
{
"input": {
"amount": 10.92,
"currency": "GBP"
},
"output": {
"AED": 46.023890640000005,
}
}
Run Code Online (Sandbox Code Playgroud)
如果我退货:
{ "input": { "amount": 10.92, "currency": "GBP" },"output": {"AED": …Run Code Online (Sandbox Code Playgroud)