Home > front end >  How can I get correct order in Python dictionary
How can I get correct order in Python dictionary

Time:12-20

I don't know why my dictionary object cannot show as correct order.

 with open("data.txt", "r") as data:
    for line in data:
        json_line = json.loads(line.strip())
        if json_line["Product_ID"] == id:
            return jsonify(json_line), 200

Original order is

{"Product_ID": "010", "Product_dec": "orange", "price": 21, "Quantity": 2}

But the output is

{"Product_ID": "010", "Product_dec": "orange", "Quantity": 2, "price": 21}

CodePudding user response:

If you use a python version newer than 3.6 the only thing you need to do is to set the JSON_SORT_KEYS for Flask on False:

app.config["JSON_SORT_KEYS"] = False

For older python version you will need to use the json.loads like this:

json_line = json.loads(line.strip(), object_pairs_hook=OrderedDict)

Bellow is a code very similar with yours which shows the above points:

import json
from flask import Flask, jsonify
from collections import OrderedDict

app = Flask(__name__)
app.config["JSON_SORT_KEYS"] = False

with app.app_context():

    with open("D:/data.txt", "r") as data:
        for line in data:
            json_line = json.loads(line.strip(), object_pairs_hook=OrderedDict)
            print(json_line)
            if json_line["Product_ID"] == '010':
                a = jsonify(json_line), 200
                print(a[0].json)
  • Related