从api获取json格式为有用的json格式(烧瓶)

时间:2020-09-13 20:25:46

标签: python json api 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格式转换为1.格式? (我只从API获取2. json格式) 在html内编写其他查询(例如p.data.first_name)?

2 个答案:

答案 0 :(得分: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
  }
]

答案 1 :(得分:1)

您要寻找的是在传递呈现模板之前过滤并展平第二个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节点中提取子节点。

我认为为这个简单的任务拉出一个图书馆是不值得的。

相关问题