0

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.

JG1629Code
  • 11
  • 3
  • Numeric keys are always stored in numeric order. Other keys are in insertion order. – Barmar Dec 15 '22 at 18:23
  • https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Kinglish Dec 15 '22 at 18:24
  • Order does not matter in JSON, nor in Javascript. You should think of keys as being unordered. – Tim Roberts Dec 15 '22 at 18:24
  • Numeric keys are always stored in numeric order. In order to save order as you expect you can add special prefix in keys for formation non numeric keys, for example instead of {'8': 'huit'} use {'_8': 'huit'}. – Vladyslav Sharapat Dec 15 '22 at 18:33

0 Answers0