Python | Sort JSON by value



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

The challenge is to sort the JSON first by code , then by class followed by enrollment_no .

Code # 1: sort in order

# Python code to demonstrate JSON sorting.

import json

 

data = & # 39; & # 39; & # 39; {

& quot; Student & quot;: [

{

& quot; Enrollment_no & quot ;: & quot; 9915103000 & quot ;,

& quot; Title & quot ;: & quot; JIIT & quot ;,

& quot; subject & quot;: [

{

  "Code": "DBMS",

& quot; Class & quot ;: & quot; C & quot;

  }

]

< code class = "comments">},

{

& quot; Enrollment_no & quot ;: & quot; 8815103057 & quot ;,

  & quot; Title & quot ;: & quot; JSS & quot ;,

  & quot; subject & quot;: [

{

& quot; Code & quot ;: & quot; COA & quot ;,

& quot; excellent grade & quot;

},

{

& quot; Code & quot ;: & quot; CN & quot ;,

 

& quot; Class & quot ;: & quot; A + & quot;

}

]

}

  ]

} & # 39; & # 39;"

 
# Parse the Json object

json_parse = json.loads (data)

 
# repeat

for it in json_parse [ `Student` ]:

< code class = "undefined spaces">  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: using an external library like like Pandas (sort 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 )

Exit :

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