I create randomly ordered dict in python and import it to JS, however the dict is always reordered in JS as per my console log:
Python:
def generate_translation(language):
dictionary = DICTIONARIES[language]
words = list(dictionary.keys())
random.shuffle(words)
test = dict()
for key in words:
test[key]=dictionary[key]
js_test = json.dumps(test)
with open(os.path.join("/workspaces/78624234/CS50X/project/static", "js_test.json"), "w") as f:
f.write(js_test)
f.close
return test, js_test
...
test, js_test = generate_translation(selected)
return render_template("study.html", language=selected, dictionary=test, js_dictionary=js_test)
JavaScript:
import data from './js_test.json' assert { type: 'json'};
var dict = data;
JSON File:
{"8": "huit", "5": "cinq", "3": "trois", "9": "neuf", "2": "deux", "1": "un", "4": "quatre", "10": "dix", "7": "sept", "6": "six"}
Console:
{1: 'un', 2: 'deux', 3: 'trois', 4: 'quatre', 5: 'cinq', 6: 'six', 7: 'sept', 8: 'huit', 9: 'neuf', 10: 'dix'}
I expected importing would maintain the format of the stored JSON file but it always defaults to ascending order. I tired rewriting line 2 of my JS file to be var dict = JSON.parse(data) but this returned a syntax error.