How to compare JSON objects regardless of order in Python?
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primarily for data transmission between server and web applications. .
In this article, we will be learning about how can we compare JSON objects regardless of the order in which they exist in Python.
- Import module
- Create JSON strings
- Convert strings to python dictionaries
- Sort dictionaries
- Print result
Various implementation to do the same is given below,
Example 1: Using sorted()
Example 2: More complex comparison
[(‘CEO’, ‘Sandeep Jain’), (‘Class’, ‘Website’), (‘Domain’, ‘CS/IT’), (‘Name’, ‘GFG’), (‘Subjects’, [‘DSA’, ‘Python’, ‘C++’, ‘Java’])]
[(‘CEO’, ‘Sandeep Jain’), (‘Class’, ‘Website’), (‘Domain’, ‘CS/IT’), (‘Name’, ‘GFG’), (‘Subjects’, [‘C++’, ‘Python’, ‘DSA’, ‘Java’])]
In this case we get our result as False because the problem with sorted() method is it only works on the top-level of a dictionary i.e., onto the keys and not on their values as can be verified by above code. So, in such cases we can define a custom function ourselves that can recursively sort any list or dictionary (by converting dictionaries into a list of key-value pair) and thus they can be made fit for comparison. Implementation using this alternative is given below.