如何让 JS fetch 按照 Flask 发送的顺序从 Flask API 接收 json/数据?
烧瓶API:
@api_bp.route("/users")
def users():
all_users = User.query.all()
data = list([u.to_dict() for u in all_users])
return data
打印(数据):
[{'id': 1, 'username': 'godo', 'email': '[email protected]', 'first_name': 'Godo', 'last_name': 'xxx'}]
JS脚本:
fetch( apiEndpoint + 'users' )
.then(response => response.json())
.then(data => {
this.tableData = data;
})
.catch(error => {
console.error('Error fetching data:', error);
});
数据:
[{'email': '[email protected]', 'first_name': 'Godo', 'id': 1, 'last_name': 'xxx', 'username': 'godo'}]
JS fetch 接收到的 JSON 键的顺序被更改为看似按字母顺序或随机顺序。我读到有关于为什么会出现这种情况的技术解释,但我确实需要以相同的顺序接收数据。原因:我将在浏览器中使用 Bootstrap-vue 显示这些数据,并且顺序很重要。
JavaScript 中不保证 JSON 对象中键的顺序,因此该顺序可能与 Flask 发送的顺序不同。但是,您可以使用数组来指定键的顺序,然后将数据映射到具有所需顺序的键的新对象。
fetch(apiEndpoint + 'users')
.then(response => response.json())
.then(data => {
const orderedData = data.map(obj => {
return keyOrder.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
});
this.tableData = orderedData;
})
.catch(error => {
console.error('Error fetching data:', error);
});