Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Counting Sort - Python
Next article icon

Python JSON Sort

Last Updated : 01 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In the world of programming, managing and manipulating data is a fundamental task. JSON (JavaScript Object Notation) is a widely used data interchange format due to its simplicity and human-readable structure. When working with JSON data in Python, sorting becomes essential for better organization and analysis. In this article, we will explore different of Python JSON sort and delve into different methods to achieve it.

Python JSON Sort

Below, are the methods of Python JSON Sort in Python:

  • Using sorted() Function
  • Using itemgetter() Module
  • Using Custom Sorting Function

Python JSON Sort Using sorted() Function

In this example, the below code begins by importing the `json` module in Python. It then initializes a sample JSON data string (`json_data`) and converts it into a Python dictionary (`data_dict`) using `json.loads`. Subsequently, the script showcases sorting the dictionary based on keys and values, and the sorted results are printed.

Python3
import json  # Sample JSON data json_data = '{"c": 3, "a": 1, "b": 2}'  # Parse JSON into a Python dictionary data_dict = json.loads(json_data)  # Sort based on keys sorted_data_keys = json.dumps({k: data_dict[k] for k in sorted(data_dict)})  # Sort based on values sorted_data_values = json.dumps({k: v for k, v in sorted(data_dict.items(), key=lambda item: item[1])})  print("Sorted based on keys:", sorted_data_keys) print("Sorted based on values:", sorted_data_values) 

Output
Sorted based on keys: {"a": 1, "b": 2, "c": 3} Sorted based on values: {"a": 1, "b": 2, "c": 3} 

Python JSON Sort Using itemgetter() Module

In this example, below Python code utilizes the `json` module to parse a JSON array into a list of dictionaries. The script then employs `sorted` with `itemgetter('age')` to sort the list based on the 'age' key. The result is printed, showcasing the sorted list of dictionaries by age.

Python3
import json from operator import itemgetter  # Sample JSON array of dictionaries json_array = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 22}]'  # Parse JSON into a Python list of dictionaries data_list = json.loads(json_array)  # Sort based on the 'age' key sorted_data_age = json.dumps(sorted(data_list, key=itemgetter('age')))  print("Sorted based on age:", sorted_data_age) 

Output
Sorted based on age: [{"name": "Charlie", "age": 22}, {"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}] 

Python JSON Sort Using a Custom Sorting Function

In this example, below Python code begins by parsing a JSON array of dictionaries into a Python list using the `json` module. It then defines a custom sorting function based on the length of the 'name' key. The list of dictionaries is subsequently sorted using this custom function, and the result is printed.

Python3
import json  # Sample JSON array of dictionaries json_array = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 22}]'  # Parse JSON into a Python list of dictionaries data_list = json.loads(json_array)  # Custom sorting function based on the length of 'name' def custom_sort(item):     return len(item['name'])  # Sort based on the custom function sorted_data_custom = json.dumps(sorted(data_list, key=custom_sort))  print("Sorted based on custom function:", sorted_data_custom) 

Output
Sorted based on custom function: [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}, {"name": "Charlie", "age": 22}] 

Conclusion

In conclusion , Python JSON sort is a valuable skill for anyone working with JSON data in Python. By understanding and implementing the various sorting methods demonstrated in this article, you can efficiently organize and present your data in a way that suits your specific needs. Whether sorting based on keys, values, or custom criteria, these techniques empower you to make the most out of your JSON data.


Next Article
Counting Sort - Python

P

pratyushds26
Improve
Article Tags :
  • Python
  • Python Programs
  • Python json-programs
Practice Tags :
  • python

Similar Reads

  • Insertion Sort - Python
    Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. The insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the length is 0 or
    3 min read
  • Comb Sort - Python
    Comb Sort is an improvement over Bubble Sort, and it aims to eliminate the problem of small values near the end of the list, which causes Bubble Sort to take more time than necessary. Comb Sort uses a larger gap for comparison, which gradually reduces until it becomes 1 (like the gap in Shell Sort).
    3 min read
  • Python | Sort JSON by value
    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 array
    2 min read
  • Counting Sort - Python
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    7 min read
  • Python Json To List
    JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used in web development and data exchange. In Python, converting JSON to a list is a common task, and there are several methods available to achieve this. In this article, we will explore four simple and commonly used
    2 min read
  • Cycle Sort - Python
    Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It is optimal in terms of several memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s
    3 min read
  • Bubble Sort - Python
    Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Bubble Sort algorithm, sorts an array by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The algorithm iterates through the a
    2 min read
  • Sort a Dictionary - Python
    In Python, dictionaries store key-value pairs and are great for organizing data. While they weren’t ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether you’re arranging names alphabetically or sorting scores from highest to lowest, P
    5 min read
  • Sort a list in python
    Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting. [GFGTABS] Python # Initializing a list a = [5, 1, 5, 6] # Sort modifies the given list a.sort() print(a) b = [5, 2, 9, 6] # Sorted does not m
    5 min read
  • Python - Nearest K Sort
    Given a List of elements, perform sort on basis of its distance from K. Input : test_list = [6, 7, 4, 11, 17, 8, 3], K = 10 Output : [11, 8, 7, 6, 4, 17, 3] Explanation : 11-10 = 1; < 10 - 8 = 2 .. Ordered by increasing difference. Input : test_list = [6, 7, 4, 11], K = 10 Output : [11, 7, 6, 4]
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences