Python 将api中的json格式转换为有用的json格式(flask)
我想通过flask将json格式的数据插入webapp,以将值转换为html: spec_player.html:Python 将api中的json格式转换为有用的json格式(flask),python,json,api,flask,Python,Json,Api,Flask,我想通过flask将json格式的数据插入webapp,以将值转换为html: spec_player.html: {% for p in posts: %} <p>{{p.first_name}}</p> {% endfor %} 这不起作用(main.py): 我想知道是否有办法得到2。将json格式转换为1。格式?(我只从api获取2.json格式) 或 在html中编写其他查询(如p.data.first\u name)?如果总是以第二种格式检索输入数据
{% for p in posts: %}
<p>{{p.first_name}}</p>
{% endfor %}
在html中编写其他查询(如p.data.first\u name)?如果总是以第二种格式检索输入数据,则可以将其转换为第一种格式,如下所示:
导入itertools
展平=itertools.chain.from_iterable
def转换(POST):
转换=列表(映射(lambda post:post[“数据”],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
}
]
您需要的是在传递到呈现模板之前过滤并展平第二个
帖子
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(但可读性较差)的版本
然后将展开的json作为
return render_template("spec_player.html", posts=fatten(posts))
这两个函数都在POST JSON上迭代,并提取每个data
节点中的子节点
我认为为这个简单的任务拉一个库是不值得的。这很有效。是否可以将数据保存在[]中?我需要他们访问变量。@fid我不确定我是否理解你的要求,请你将你想要实现的示例粘贴到某个地方好吗?我需要这样的表格:
[{“id”:237,“first\u name”:“LeBron”,“height\u feet”:6,“height\u inches”:8,“last\u name”:“James”,“position”:“F”,“team”:{“id”:14,“缩写”:“LAL”,“city”:“Los Angeles”,“会议”:“西部”、“分区”:“太平洋”、“全名”:“洛杉矶湖人队”、“姓名”:“湖人队”},“体重”:250}]
所以方括号应该保留。看起来它的格式与您的帖子中的格式-1相同。如果您需要无扁平化,如下所示:[[{'id':237,'名字':'勒布朗','身高英尺':6,'身高英寸':8,'姓氏':'詹姆斯','位置':'F','球队':{'id':14,'缩写':'拉尔','城市':'洛杉矶','会议':'西部','分区':'太平洋','全名':'洛杉矶湖人','名字':'湖人','体重':250}]
,然后只需删除展平
调用(在转换函数中)
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
def flatten(json):
return [item for node in json if node["data"] is not None for item in node["data"]]
return render_template("spec_player.html", posts=fatten(posts))