Dan*_*Dan 4 python api json flask flask-sqlalchemy
我在 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
Run Code Online (Sandbox Code Playgroud)
小智 5
您在这里的理解中缺少的是,当您在 Python 中使用 JSON 模块时,您并不是在使用 JSON 对象。JSON 根据定义只是一个符合特定标准的字符串。
假设您有字符串:
friends = '{"name": "Fred", "id": 1}'
Run Code Online (Sandbox Code Playgroud)
如果你想在 python 中使用这些数据,你需要将其加载到 python 对象中:
import json
friends_obj = json.loads(friends)
Run Code Online (Sandbox Code Playgroud)
此时friends_obj就是一个python字典。
如果你想转换它(或任何其他 python 字典或列表),那么 json.dumps 就派上用场了:
friends_str = json.dumps(friends_obj)
print friends_str
'{"name": "Fred", "id": 1}'
Run Code Online (Sandbox Code Playgroud)
但是,如果我们尝试“转储”原始朋友字符串,您会看到不同的结果:
dumped_str = json.dumps(friends)
print dumped_str
'"{\\"name\\": \\"Fred\\", \\"id\\": 1}"'
Run Code Online (Sandbox Code Playgroud)
这是因为您基本上是在尝试将普通字符串编码为 JSON,并且它正在转义字符。我希望这有助于理解事情!
干杯