Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Python JSON

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Regular Expressions (RegEx)
  • Python JSON

IC_Python_Tutorial-22_Python_JSON.png

Python JSON (JavaScript Object Notation)¶

Introduction to JSON in Python¶

  • JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data.
  • Python provides a built-in json module for working with JSON.
  • JSON is widely used in web applications, APIs, and data exchange.

Parsing JSON: Convert JSON to Python¶

  • The json.loads() method converts a JSON-formatted string into a Python dictionary.
In [ ]:
import json

# JSON data as a string
json_data = '{ "name": "Alice", "age": 25, "city": "London"}'

# Convert JSON string to Python dictionary
python_dict = json.loads(json_data)

# Access values from the dictionary
print(python_dict["name"])  # Output: Alice
print(python_dict["age"])   # Output: 25
Alice
25

Converting Python Objects to JSON¶

  • The json.dumps() method converts Python objects into a JSON string.
  • Supported Python data types for conversion:
    • dict, list, tuple, str, int, float, bool, None
In [ ]:
import json

# Python dictionary
data = {
    "name": "Alice",
    "age": 25,
    "city": "London"
}

# Convert to JSON string
json_string = json.dumps(data)

print(json_string)  # Output: {"name": "Alice", "age": 25, "city": "London"}
{"name": "Alice", "age": 25, "city": "London"}

Example Conversions¶

In [ ]:
print(json.dumps({"language": "Python", "version": 3.10}))  # Dictionary to JSON
print(json.dumps(["ML", "AI", "Deep Learning"]))            # List to JSON
print(json.dumps(("NLP", "Computer Vision")))               # Tuple to JSON
print(json.dumps(42))                                       # Integer to JSON
print(json.dumps(19.99))                                    # Float to JSON
print(json.dumps(True))                                     # Boolean to JSON
print(json.dumps(None))                                     # None to JSON
{"language": "Python", "version": 3.1}
["ML", "AI", "Deep Learning"]
["NLP", "Computer Vision"]
42
19.99
true
null

Python to JSON Mapping¶

Python Data Type JSON Equivalent
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

Working with Complex JSON Data¶

  • JSON can store nested data structures like lists and dictionaries.
In [ ]:
import json

# Complex Python data structure
user_profile = {
    "name": "Alice",
    "age": 25,
    "skills": ["Python", "Machine Learning"],
    "education": {
        "degree": "MSc",
        "field": "Computer Science"
    },
    "certified": True
}

# Convert Python dictionary to JSON
json_data = json.dumps(user_profile)

print(json_data)
{"name": "Alice", "age": 25, "skills": ["Python", "Machine Learning"], "education": {"degree": "MSc", "field": "Computer Science"}, "certified": true}

Formatting JSON Output¶

  • JSON output can be formatted for readability using indent.
In [ ]:
import json

# Nested dictionary
data = {
    "name": "Alice",
    "age": 25,
    "skills": ["Python", "Data Science"],
    "projects": [
        {"title": "NLP Model", "status": "Completed"},
        {"title": "Computer Vision", "status": "In Progress"}
    ]
}

# Convert to JSON with indentation
formatted_json = json.dumps(data, indent=4)

print(formatted_json)

### **Output:**
# {
#     "name": "Alice",
#     "age": 25,
#     "skills": [
#         "Python",
#         "Data Science"
#     ],
#     "projects": [
#         {
#             "title": "NLP Model",
#             "status": "Completed"
#         },
#         {
#             "title": "Computer Vision",
#             "status": "In Progress"
#         }
#     ]
# }
{
    "name": "Alice",
    "age": 25,
    "skills": [
        "Python",
        "Data Science"
    ],
    "projects": [
        {
            "title": "NLP Model",
            "status": "Completed"
        },
        {
            "title": "Computer Vision",
            "status": "In Progress"
        }
    ]
}

Customizing JSON Separators¶

  • The default separator in JSON output is ", " for items and ": " for key-value pairs.
  • We can change the separators for a more compact output.
In [ ]:
import json

data = {
    "name": "Alice",
    "age": 25,
    "skills": ["Python", "Data Science"]
}

# Custom separator
compact_json = json.dumps(data, indent=4, separators=(". ", " = "))

print(compact_json)
### **Output:**
# {
#     "name" = "Alice".
#     "age" = 25.
#     "skills" = [
#         "Python".
#         "Data Science"
#     ]
# }
{
    "name" = "Alice". 
    "age" = 25. 
    "skills" = [
        "Python". 
        "Data Science"
    ]
}

Sorting Keys in JSON Output¶

  • The sort_keys=True parameter sorts the dictionary keys alphabetically.
In [ ]:
import json

data = {
    "age": 25,
    "name": "Alice",
    "city": "London"
}

# Convert to JSON with sorted keys
sorted_json = json.dumps(data, indent=4, sort_keys=True)

print(sorted_json)
### **Output:**
# {
#     "age": 25,
#     "city": "London",
#     "name": "Alice"
# }
{
    "age": 25,
    "city": "London",
    "name": "Alice"
}
Category
Python Natural Language Processing
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing

Tag's

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer