【问题标题】:parsing string as dict in nested json document在嵌套的json文档中将字符串解析为dict
【发布时间】: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?

标签: python flask jinja2


【解决方案1】:

你快到了。服务器以无效的 json 响应有点奇怪。无论如何,仔细检查将'{ 替换为{}' 替换为} 不会把事情搞砸。我刚刚修改了您的示例,如下所示:

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)

【讨论】:

  • 我最终使用了json.loads,这个也可以。谢谢
猜你喜欢
  • 2016-02-21
  • 2019-11-04
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多