Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Sort JSON by value

  • Last Updated : 12 Feb, 2019

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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
# Parsing Json object
json_parse = json.loads(data)
# iterating 
for it in json_parse['Student']:
    for y in it['subject']:

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 import json_normalize
df = json_normalize(json_parse['Student'],
                    ['enrollment_no', 'name'])
df.sort_values(['code', 'grade', 'enrollment_no']).reset_index(drop=True)


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

My Personal Notes arrow_drop_up
Recommended Articles
Page :