【问题标题】:Getting json-format from api into useful json-format (flask)从 api 获取 json-format 到有用的 json-format (flask)
【发布时间】:2020-12-31 15:21:51
【问题描述】:

我想通过flask将json格式的数据插入到webapp中以将值放入html:

spec_player.html:

{% for p in posts: %}
    <p>{{p.first_name}}</p>
{% endfor %}
  1. 这有效 (main.py):
posts = [
    {
        "id":237,"first_name":"LeBron","height_feet":6,"height_inches":8,"last_name":"James","position":"F",
        "team":{"id":14,"abbreviation":"LAL","city":"Los Angeles","conference":"West","division":"Pacific","full_name":"Los Angeles Lakers","name":"Lakers"},"weight_pounds":250
    }
]

@app.route("/spec")
def spec_player():
    return render_template("spec_player.html", posts=posts)
  1. 这不起作用(main.py):
posts = [
    {
        "data":[{"id":237,"first_name":"LeBron","height_feet":6,"height_inches":8,"last_name":"James","position":"F",
        "team":{"id":14,"abbreviation":"LAL","city":"Los Angeles","conference":"West","division":"Pacific","full_name":"Los Angeles Lakers","name":"Lakers"},"weight_pounds":250}],
        "meta":{"total_pages":1,"current_page":1,"next_page":null,"per_page":25,"total_count":1}
    }
]

@app.route("/spec")
def spec_player():
    return render_template("spec_player.html", posts=posts)

不知道有没有办法把 2.json-format 变成 1.format? (我只从 api 获得 2.json 格式) 在 html 中编写另一个查询(类似于 p.data.first_name)?

【问题讨论】:

    标签: python json api flask


    【解决方案1】:

    如果您总是以第二种格式检索输入数据,您可以将其转换为第一种格式,如下所示:

    import itertools
    flatten = itertools.chain.from_iterable
    
    def transform(posts):
        transformed = list(map(lambda post: post["data"], posts))
        flat_posts = list(flatten(transformed))
        return flat_posts
    

    示例:

    posts = [
        {
            "data":[{"id":237,"first_name":"LeBron","height_feet":6,"height_inches":8,"last_name":"James","position":"F",
            "team":{"id":14,"abbreviation":"LAL","city":"Los Angeles","conference":"West","division":"Pacific","full_name":"Los Angeles Lakers","name":"Lakers"},"weight_pounds":250}],
            "meta":{"total_pages":1,"current_page":1,"next_page":None,"per_page":25,"total_count":1}
        }
    ]
    
    print(transform(posts))
    
    >>> [
      {
        'id': 237, 'first_name': 'LeBron', 'height_feet': 6, 'height_inches': 8, 'last_name': 'James', 'position': 'F', 
        'team': {'id': 14, 'abbreviation': 'LAL', 'city': 'Los Angeles', 'conference': 'West', 'division': 'Pacific', 'full_name': 'Los Angeles Lakers', 'name': 'Lakers'}, 'weight_pounds': 250
      }
    ]
    
    

    【讨论】:

    • 这很好用。是否可以保留数据所在的 [ ] ?我需要它们来访问变量。
    • @fid 我不确定我是否理解您的要求,您能否在某处粘贴您想要实现的示例?
    • 我需要这样的表格:[{"id":237,"first_name":"LeBron","height_feet":6,"height_inches":8,"last_name":"James","position":"F", "team":{"id":14,"abbreviation":"LAL","city":"Los Angeles","conference":"West","division":"Pacific","full_name":"Los Angeles Lakers","name":"Lakers"},"weight_pounds":250}] 所以方括号应该保留。
    • 看起来与您帖子中的 format-1 格式相同。如果您需要不进行展平,例如:[[{'id': 237, 'first_name': 'LeBron', 'height_feet': 6, 'height_inches': 8, 'last_name': 'James', 'position': 'F', 'team': {'id': 14, 'abbreviation': 'LAL', 'city': 'Los Angeles', 'conference': 'West', 'division': 'Pacific', 'full_name': 'Los Angeles Lakers', 'name': 'Lakers'}, 'weight_pounds': 250}]] ,则只需删除 flatten 调用(在变换函数中)
    【解决方案2】:

    您正在寻找的是过滤和展平第二个posts JSON,然后再传递给渲染模板。例如,你可以这样做;

    def fatten(json):
        flatten_json = []
        for node in json:
            d = node["data"]
            if d is not None:
                for item in d:
                    flatten_json.append(item)
        return flatten_json
    
    

    或更多 Pythonic(但不那么可读)的版本

    def flatten(json):
        return [item for node in json if node["data"] is not None for item in node["data"]]
    

    然后将扁平化的json传递为

    return render_template("spec_player.html", posts=fatten(posts))
    

    这两个函数都会遍历 JSON 帖子并提取每个 data 节点中的子节点。

    我不认为为这个简单的任务拉一个库是值得的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2022-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多