The Wayback Machine - https://web.archive.org/web/20250112193737/https://www.geeksforgeeks.org/python-sort-json-by-value/
Open In App

Python | Sort JSON by value

Last Updated : 12 Feb, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let’s see the different ways to sort the JSON data using Python.

What is JSON ?
JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

The task is to sort the JSON first by code, then by grade and then by enrollment_no .

Code #1: Sorting in Desc order




# Python code to demonstrate sorting in JSON.
import json
  
data='''{  
   "Student":[  
      {  
         "enrollment_no":"9915103000",
         "name":"JIIT",
         "subject":[  
            {  
               "code":"DBMS",
               "grade":"C"
            }
         ]
      },
      {  
         "enrollment_no":"8815103057",
         "name":"JSS",
         "subject":[  
            {  
               "code":"COA",
               "grade":"A"
            },
            {  
               "code":"CN",
               "grade":"A+"
            }
         ]
      }
   ]
}'''
  
# Parsing Json object
json_parse = json.loads(data)
   
# iterating 
for it in json_parse['Student']:
    for y in it['subject']:
        print(y['code'],y['grade'],it['enrollment_no'],it['name'])


Output :

DBMS C 9915103000 JIIT
COA A 8815103057 JSS
CN A+ 8815103057 JSS

 
Code #2 : By using External library such as Pandas (Sorting in Ascending order).




from pandas.io.json import json_normalize
  
df = json_normalize(json_parse['Student'],
                               'subject', 
                    ['enrollment_no', 'name'])
  
df.sort_values(['code', 'grade', 'enrollment_no']).reset_index(drop=True)


Output:

  code grade  enrollment_no      name
0  CN     A+  8815103057         JSS
1  COA    A  8815103057         JSS
2  DBMS   C  9915103000        JIIT

Learn Python from scratch with our Python Full Course Online, designed for beginners and advanced learners alike. Master everything from Python basics to advanced python concepts with hands-on practice and projects.


Take the Three 90 Challenge! Finish 90% of the course in 90 days, and receive a 90% refund. Stay on track, keep progressing, and get rewarded for your hard work.
Start today and become a Python pro!


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg