2 回答
![?](http://img1.sycdn.imooc.com/54584f9d0001219b02200220-100-100.jpg)
TA贡献1804条经验 获得超8个赞
如果您总是以第二种格式检索输入数据,您可以将其转换为第一种格式,如下所示:
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
}
]
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
TA贡献1811条经验 获得超5个赞
您需要的是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))
这两个函数都会迭代 posts JSON 并提取每个data节点中的子节点。
我认为为这个简单的任务拉一个库是不值得的。
添加回答
举报