-2

How do I make JS fetch receive json/data from flask API in the same order as sent by flask?

flask API:

@api_bp.route("/users")
def users():
    all_users = User.query.all()
    data = list([u.to_dict() for u in all_users])
    return data

print(data):

[{'id': 1, 'username': 'godo', 'email': '[email protected]', 'first_name': 'Godo', 'last_name': 'xxx'}]

JS script:

fetch( apiEndpoint + 'users' )
.then(response => response.json())
.then(data => {
  this.tableData = data;
})
.catch(error => {
  console.error('Error fetching data:', error);
});

data:

[{'email': '[email protected]', 'first_name': 'Godo', 'id': 1, 'last_name': 'xxx', 'username': 'godo'}]

The order of keys of the JSON when received by JS fetch is altered to a seemingly alphabetical or random order. I have read that there are technical explanations as to why this is the case, but I really need to receive the data in the same order. Reason: I will display this data using Bootstrap-vue in the browser, and the order is important.

6
  • 2
    Order of object properties in JavaScript objects is not something you can control and definitely not something you should rely on. Commented Nov 19, 2023 at 17:00
  • 1
    If the order is important, fetch the keys according to an array that establishes the ordering you need. Commented Nov 19, 2023 at 17:01
  • Also you might want to check what the actual JSON payload looks like (the browser Network developer tab will show you that.) Commented Nov 19, 2023 at 17:11
  • maybe you should keep in different format - ie. list of lists [ ['id', 1], ['username', 'godo'], ['email', ...], ...] but maybe it also may need to change code in `Bootstrap-vue Commented Nov 20, 2023 at 0:41
  • 1
    @JeffP the ordering isn't guaranteed on the Python side either so you will have to perform some sort of sort into a linear data structure. Commented Nov 21, 2023 at 14:07

1 Answer 1

1

The order of the keys in the JSON object is not guaranteed in JavaScript, so the order can be different from the order in which it was sent by Flask. However, you can use an array to specify the order of the keys and then map the data to a new object with the keys in the desired order.

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);
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.