[英]parsing string as dict in nested json document
In my flask app, I get a json response from an external api call which has nested documents.在我的 flask 应用程序中,我从具有嵌套文档的外部 api 调用中获得了 json 响应。 I noticed one of the fields in the nested document is a string which I'd like to parse as dictionary so I can extract the fields in my html page?我注意到嵌套文档中的一个字段是一个字符串,我想将其解析为字典,以便可以提取 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)
I want to be able to extract content
like this in my html:我希望能够在我的 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>
You are almost there.你快到了。 It is kinda strange the server is responding with an invalid json.服务器响应无效的 json 有点奇怪。 Anyways, double check replacing '{
by {
and }'
by }
is not going to screw thing up.无论如何,仔细检查用 { 替换'{
{
用}
替换}'
不会把事情搞砸。 I just modified your example a little bit like below:我刚刚修改了您的示例,如下所示:
import json
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route('/')
def index():
template = """
<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>
"""
payload = """
[
{
"full_name": "John Doe",
"email": "jdoe@example.com",
"content": '{"count":10, "info": {"foo": "bar", "location": "LA"}, "items":["A", "B", "C"]}'
}
]
""".replace("'{", "{").replace("}'", "}")
data = json.loads(payload)
return render_template_string(template, data=data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.