Home  >  Article  >  Backend Development  >  How do I control the order of keys when converting a Python dictionary to JSON using \"json.dumps\"?

How do I control the order of keys when converting a Python dictionary to JSON using \"json.dumps\"?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 07:45:30577browse

How do I control the order of keys when converting a Python dictionary to JSON using

JSON Object Key Ordering with "json.dumps"

Problem:

When converting a Python dictionary to a JSON object using "json.dumps," the order of the keys may not be as expected. The desired order (e.g., "id," "name," "timezone") is not being maintained.

Solution:

1. Sort Keys:

To specify the desired key order, pass the "sort_keys" parameter to "json.dumps." This parameter sorts the keys in ascending order.

json.dumps(countries, sort_keys=True)

2. Use "OrderedDict":

For precise control over the key order, use the "OrderedDict" from the "collections" module instead of a regular dictionary. The order of keys in "OrderedDict" is preserved upon conversion to JSON.

Python 3.7 and Below:

import json
from collections import OrderedDict

ordered_countries = OrderedDict([("id", row.id), ("name", row.name), ("timezone", row.timezone)])
print(json.dumps(ordered_countries))

Python 3.8 and Above:

import json
from collections import OrderedDict

ordered_countries = OrderedDict()
ordered_countries["id"] = row.id
ordered_countries["name"] = row.name
ordered_countries["timezone"] = row.timezone
print(json.dumps(ordered_countries))

3. Preserving Input Order (JSON):

If the input is already a JSON object and you want to preserve its key order in the output, pass the "object_pairs_hook" parameter to "json.loads." This parameter takes a callable that returns an "OrderedDict" based on the key-value pairs of the JSON object.

import json
from collections import OrderedDict

input_json = '{"a": 1, "b": 2}'
ordered_json = json.loads(input_json, object_pairs_hook=OrderedDict)

The above is the detailed content of How do I control the order of keys when converting a Python dictionary to JSON using \"json.dumps\"?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn