Python将JSON返回为字符串而不是li

2024-04-28 15:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在RoR中做了一些编码,在Rails中,当我通过API调用返回JSON对象时,它返回如下

{ "id" : "1", "name" : "Dan" }

但是在Python中(使用Flask和Flask SQLAlchemy),当我通过JSON.dumps或jsonpickle.encode返回一个JSON对象时,它将返回为

"{ \"id\" : \"1\", \"name\": \"Dan\" }"这看起来非常笨拙,因为它不容易在另一端解析(在本例中是由iOS应用程序-Obj-C解析)。

我在这里遗漏了什么,我应该如何将其作为JSON文本而不是JSON字符串返回?

这就是我的代码:

people = models.UserRelationships.query.filter_by(user_id=user_id, active=ACTIVE_RECORD)
friends = people.filter_by(friends=YES)

json_object = jsonpickle.encode(friends.first().as_dict(), unpicklable=False, keys=True)
print(json_object)  # this prints here, i.e. { "id" : "1", "name" : "Dan" }

return json_object # this returns "{ \"id\" : \"1\", \"name\": \"Dan\" }" to the browser

Tags: 对象nameidjsonflaskbyobjectfilter
3条回答

看起来你在用Django,在这种情况下

from django.utils import simplejson as json
...
return HttpResponse(json.dumps(friends.first().as_dict()))

您在这里缺少的是,当您在Python中使用JSON模块时,您没有使用JSON对象。根据定义,JSON只是一个符合特定标准的字符串。

假设你有绳子:

friends = '{"name": "Fred", "id": 1}'

如果要在python中使用此数据,则需要将其加载到python对象中:

import json
friends_obj = json.loads(friends)

此时,friends_obj是一本python字典。

如果您想转换它(或任何其他python字典或列表),那么json.dumps就是在这里派上用场的:

friends_str = json.dumps(friends_obj)
print friends_str
'{"name": "Fred", "id": 1}'

但是,如果我们尝试“转储”原始的friends字符串,您将看到一个不同的结果:

dumped_str = json.dumps(friends)
print dumped_str
'"{\\"name\\": \\"Fred\\", \\"id\\": 1}"'

这是因为您基本上尝试将普通字符串编码为JSON,并且它正在转义字符。我希望这有助于理解事情!

干杯

您应该使用flask.jsonify,这样不仅可以正确编码,还可以相应地设置content-type头。

people = models.UserRelationships.query.filter_by(user_id=user_id, active=ACTIVE_RECORD)
friends = people.filter_by(friends=YES)

return jsonify(friends.first().as_dict())

相关问题 更多 >