Dictionary Wrong Order - Json

Dictionary wrong order - JSON

To post what has already been said in comments: Dictionaries are "unordered collections". They do not have any order at all to their key/value pairs. Period.

If you want an ordered collection, use something other than a dictionary. (an array of single-item dictionaries is one way to do it.) You can also write code that loads a dictionary's keys into a mutable array, sorts the array, then uses the sorted array of keys to fetch key/value pairs in the desired order.

You could also create your own collection type that uses strings as indexes and keeps the items in sorted order. Swift makes that straightforward, although it would be computationally expensive.

how to keep order of sorted dictionary passed to jsonify() function?

Add this config line to your code after the app definition:

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

How to keep the original order when read the JSON string about iOS development?

A JSON object is define in the JSON spec as an unordered collection.

An object is an unordered set of name/value pairs.
(http://json.org/)

Here are some possible solutions:

  1. Change the JSON object to an array of objects. If you control the server this is by far the best option. If order is important the an array is the right choice.
  2. Send the order along with the JSON. You can have an array of the keys also included in the JSON. Again, you would need to have control of the server to do this.
  3. Sort the keys after you get them. This can only work if the order that you want can be derived from the keys. For example if the keys are alphabetical or are numbers. If you control the keys (even if you don't control the entire server response) you can hack this by change the keys to be sortable in a way that works for you (for example change the keys from ["stores","locations"] to ["0_stores","1_locations"]. This can also work if you know all the possible keys and their order.
  4. Order the keys by the location in the JSON dictionary. If the keys in the JSON are guaranteed to not show up any where else in the JSON (i.e. there is no arbitrary text field in the JSON) then you can get all the dictionary keys sorted by looking where they appear in the JSON string:

    NSArray* sortedKeys = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString*  key1, NSString* key2) {
    NSInteger location1 = [jsonString rangeOfString:key1].location;
    NSInteger location2 = [jsonString rangeOfString:key2].location;
    return [@(location1) compare:@(location2)];
    }];
  5. If none of these options work for you then you would have find or create your own JSON parser that respects order. I think it will be hard to find such a library, since it would be explicitly against the JSON spec. I do not recommend this option.

How can I get correct order in Python dictionary

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)

json.dumps messes up order

Like the other answers correctly state, before Python 3.6, dictionaries are unordered.

That said, JSON is also supposed to have unordered mappings, so in principle it does not make much sense to store ordered dictionaries in JSON. Concretely, this means that upon reading a JSON object, the order of the returned keys can be arbitrary.

A good way of preserving the order of a mapping (like a Python OrderedDict) in JSON is therefore to output an array of (key, value) pairs that you convert back to an ordered mapping upon reading:

>>> from collections import OrderedDict
>>> import json
>>> d = OrderedDict([(1, 10), (2, 20)])
>>> print d[2]
20
>>> json_format = json.dumps(d.items())
>>> print json_format # Order maintained
[[1, 10], [2, 20]]
>>> OrderedDict(json.loads(json_format)) # Reading from JSON: works!
OrderedDict([(1, 10), (2, 20)])
>>> _[2] # This works!
20

(Note the way the ordered dictionary is constructed from a list of (key, value) pairs: OrderedDict({1: 10, 2: 20}) would not work: its keys are not necessarily ordered as in the dictionary literal, since the literal creates a Python dictionary whose keys are unordered.)

PS: Starting with Python 3.1, the json modules offers a hook for automatically converting a list of pairs (like above) to something else like an OrderedDict.

Python 3 json.load() reads JSON file in wrong order

If order is a must you can load it directly into python's OrderedDict

from collections import OrderedDict
import json
j = json.load(jsonFile, object_pairs_hook=OrderedDict)

How to read dictionaries in list of dictionaries in python

If I understand your issue correctly, the issue is that sets don't maintain insertion order.

You can maintain a list (which maintains order) and a separate set (for quickly checking whether you've seen a key already). For each key that you see, check whether it's a member of the set; if not, add it to the list and the seen keys set:

result = []
seen_keys = set()
for item in data:
for key in item:
if key not in seen_keys:
seen_keys.add(key)
result.append(key)

print(result)

With the given data, this will (deterministically!) output:

['747797252105306212', '695390884291674153']

Converting NSDictionary to Json String causes re-ordering of elements

You cannot and should not rely on the ordering of elements within a JSON object.

JSON Object is a key-value pair, there is no order, and you can't order it and last the order won't matter

For more detail check json.org



Related Topics



Leave a reply



Submit