I am trying to send a python dict to my frontend so can create some html based on the values, i therefore need the order of the dict to be reliable but when i send my dict to the frontend it changes the order. I am using python 3.11.3
this is python dict i send as a response in add_indicator()
corect
{'kind': 'ao', 'fast': 'int','slow': 'int', 'offset': 'int'}
but for some reason the response i get from postJsonString is in a diffrent order. I am using Pythin 3.11.3 so it does have ordered dicts. I have just no clue what is going on, it seems extremely strange. Anyone can enlighten me?
messed up order
{fast: 'int', kind: 'ao', offset: 'int', slow: 'int'}
PYTHON ROUTE
@bp.route('/add_indicator', methods=('POST', 'GET'))
def add_indicator():
if request.method == 'POST':
indicator = {'kind': 'ao', 'fast': 'int',
'slow': 'int', 'offset': 'int'}
indicator = jsonify(indicator)
print(indicator)
return indicator
JAVASCRIPT
async function postIt() {
let ind_props = await postJsonString(data, "/add_indicator");
console.log("after postJsonString", ind_props);
}
async function postJsonString(data, endpoint) {
let response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error("Request failed");
}
const responseData = await response.json();
return responseData;
}
Do not rely on the order of properties in an object. Especially if it passed serialisation/deserialisation as JSON.
The JSON standard says that objects are unordered list of key/value pairs.
From JSON.org:
An object is an unordered set of name/value pair
From ECMA 404 - The JSON data interchange syntax specification:
6. Objects
An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs. A name is a string. A single colon token follows each name, separating the name from the value. A single comma token separates a value from a following name. The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs. These are all semantic considerations that may be defined by JSON processors or in specifications defining specific uses of JSON for data interchange
(emphasis added)
RFC 8259 adds remarks and commentary about the state of how JSON is handled by various tools. In particular in Section 4. Objects:
JSON parsing libraries have been observed to differ as to whether or not they make the ordering of object members visible to calling software. Implementations whose behavior does not depend on member ordering will be interoperable in the sense that they will not be affected by these differences.
If order is important, use an array or some other way to represent the data that can preserve and ensures the sequencing of the data.