0

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}
wjandrea
  • 28,235
  • 9
  • 60
  • 81
So_busy
  • 15
  • 1
  • 7
  • 2
    Python dictionaries aren't ordered data structures. Why does the order matter here anyway? – jonrsharpe Dec 19 '21 at 19:39
  • 5
    What version of python are you using in generally dicts are not ordered. In later python versions they hold their order. Alternativly you can use ordered dict from the collection library – Chris Doyle Dec 19 '21 at 19:40
  • Hello, I think these answers may be useful [link](https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared), basically in python 3.6 and above dict isn't ordered. – George Imerlishvili Dec 19 '21 at 19:43
  • 2
    @GiorgiImerlishvili in newer versions it _does_ retain insertion order, but it's still not _semantically_ ordered. – jonrsharpe Dec 19 '21 at 19:43
  • 1
    Does this answer your question? [How to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared) – DYZ Dec 19 '21 at 19:45
  • Sidenote: [`id` is a bad variable name](/q/77552/4518341). You could use `product_id` instead. – wjandrea Dec 19 '21 at 20:21

1 Answers1

0

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)
Dan Constantinescu
  • 1,426
  • 1
  • 7
  • 11