"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why is the order of keys in my JSON output different from the order in my Python dictionary using `json.dumps`?

Why is the order of keys in my JSON output different from the order in my Python dictionary using `json.dumps`?

Posted on 2025-02-06
Browse:569

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:

import json

countries.append({"id":row.id,"name":row.name,"timezone":row.timezone})
print(json.dumps(countries, sort_keys=True))

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:

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))

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:

countries = {"id": row.id, "name": row.name, "timezone": row.timezone}

This will automatically preserve the order of the keys in the output JSON.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3