【发布时间】:2020-10-09 12:34:48
【问题描述】:
在我的烧瓶应用程序中,我从具有嵌套文档的外部 api 调用中获得 json 响应。我注意到嵌套文档中的一个字段是一个字符串,我想将其解析为字典,以便可以在我的 html 页面中提取字段?
import json
from flask import Flask, render_template, jsonify
import requests
app = Flask(__name__)
@app.route('/')
def index():
url = "http://remote-server/v1/info"
params = {"offset":0,"limit":10}
response = requests.post(url, json=params)
data = response.json()
print(data)
'''
>>
[
{
"full_name": "John Doe",
"email": "jdoe@example.com",
"content": '{"count":10, "info": {"foo": "bar", "location": "LA"}, "items":["A", "B", "C"]}'
}
]
'''
for item in data:
print(type(item[content]))
'''
>>
<class 'str'>
'''
return render_template('index.html', data=data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
我希望能够在我的 html 中像这样提取content:
# -- index.html
<div>
{% for doc in data %}
<div class="user_info">{{ doc['full_name'] }}</div>
<div class="user_info">{{ doc['email'] }}</div>
<div class="user_info">{{ doc['content']['info']['foo'] }}</div>
<div class="user_info">{{ doc['content']['info']['location'] }}</div>
{% for item in doc.content.items %}
<div>{{ item }}</div>
{% endfor %}
{% endfor %}
</div>
【问题讨论】:
-
好问题。但是请从您的最小工作示例中删除烧瓶依赖项。您的问题不依赖于烧瓶,它会使 MWE 更加“最小化”。
-
这能回答你的问题吗? Extract Python dictionary from string
-
是 JSON 吗?你是在问如何解析 JSON?