Home >Backend Development >Python Tutorial >Why is the order of keys in my JSON output different from the order in my Python dictionary using `json.dumps`?
Out-of-Order Items in JSON Objects with "json.dumps"?
In your code, you're using "json.dumps" to convert a list of dictionaries into JSON. However, you've noticed that the order of the keys within each dictionary is not as expected. Specifically, you need the keys to appear in the order of "id", "name", and "timezone".
Reasoning
Both Python dictionaries (before Python 3.7) and JSON objects are unordered collections. This means that the order of the keys in a dictionary or JSON object is not guaranteed.
Solution 1: Sorting Keys
You can use the "sort_keys" parameter of "json.dumps" to sort the keys in the output JSON. For example:
<code class="python">import json countries.append({"id":row.id,"name":row.name,"timezone":row.timezone}) print(json.dumps(countries, sort_keys=True))</code>
This will output JSON with the keys in the following order:
[ {"id": 1, "name": "Mauritius", "timezone": 4}, {"id": 2, "name": "France", "timezone": 2}, {"id": 3, "name": "England", "timezone": 1}, {"id": 4, "name": "USA", "timezone": -4} ]
Solution 2: Using OrderedDict
If you need a specific order for the keys, you can use the "collections.OrderedDict" class. OrderedDict preserves the order of the keys inserted into it. For example:
<code class="python">from collections import OrderedDict countries_by_id = OrderedDict() countries_by_id["id"] = row.id countries_by_id["name"] = row.name countries_by_id["timezone"] = row.timezone print(json.dumps(countries_by_id))</code>
This will output JSON with the keys in the order of "id", "name", and "timezone".
Additional Note
In Python 3.6 and later, the order of keyword arguments is preserved in dictionaries. This means that you can achieve the same result as using OrderedDict by simply specifying the keys in the desired order when creating the dictionary:
<code class="python">countries = {"id": row.id, "name": row.name, "timezone": row.timezone}</code>
This will automatically preserve the order of the keys in the output JSON.
The above is the detailed content of Why is the order of keys in my JSON output different from the order in my Python dictionary using `json.dumps`?. For more information, please follow other related articles on the PHP Chinese website!