Categories
Python Answers

How to fix items in JSON object are out of order using Python json.dumps?

Spread the love

Sometimes, we want to fix items in JSON object are out of order using Python json.dumps.

In this article, we’ll look at how to fix items in JSON object are out of order using Python json.dumps.

How to fix items in JSON object are out of order using Python json.dumps?

To fix items in JSON object are out of order using Python json.dumps, we can call json.dumps with a ordered dict.

For instance, we write

from collections import OrderedDict

s = json.dumps(OrderedDict([("a", 1), ("b", 2)]))

to create an ordered dict with the OrderDict class.

And then we call json.dumps with the ordered dict to create a JSON string that has the same order as the items are listed in the list we created the OrderedDict with.

Conclusion

To fix items in JSON object are out of order using Python json.dumps, we can call json.dumps with a ordered dict.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *