Json in Python
JSON in Python
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. JSON is used to represent structured data in a textual format, and it is commonly used for APIs and data storage.
Python provides the json module to work with JSON data. This module allows you to convert Python objects into JSON strings and vice versa.
Basic JSON Operations in Python
Converting Python objects to JSON: Using
json.dumps().Converting JSON to Python objects: Using
json.loads().
1. Converting Python Objects to JSON
The json.dumps() method is used to convert Python objects like dictionaries, lists, or tuples into a JSON string.
Example: Convert Python Dictionary to JSON String
import json# Create a Python dictionarydata = { "name": "John", "age": 30, "city": "New York"}# Convert dictionary to JSON stringjson_data = json.dumps(data)print(json_data)Output:
{"name": "John", "age": 30, "city": "New York"}In this example, the Python dictionary data is converted into a JSON string.
2. Converting JSON to Python Objects
The json.loads() method is used to convert a JSON string into a Python dictionary (or other appropriate Python object).
Example: Convert JSON String to Python Dictionary
import json# JSON stringjson_string = '{"name": "John", "age": 30, "city": "New York"}'# Convert JSON string to Python dictionarydata = json.loads(json_string)print(data)Output:
{'name': 'John', 'age': 30, 'city': 'New York'}In this example, the JSON string json_string is converted into a Python dictionary.
Working with Files: JSON File Handling
You can also work with JSON data stored in files. The json module provides methods for reading from and writing to JSON files.
3. Writing JSON to a File
You can use json.dump() to write a Python object to a JSON file.
import json# Python object (dictionary)data = { "name": "John", "age": 30, "city": "New York"}# Write Python object to a JSON filewith open('data.json', 'w') as json_file: json.dump(data, json_file)This will create a file called data.json with the following content:
{"name": "John", "age": 30, "city": "New York"}4. Reading JSON from a File
To read JSON data from a file, use json.load().
import json# Read JSON data from a filewith open('data.json', 'r') as json_file: data = json.load(json_file)print(data)Output:
{'name': 'John', 'age': 30, 'city': 'New York'}Advanced JSON Operations
Pretty Printing JSON: If you want to make the JSON output more readable (i.e., pretty-print it), you can use the
indentparameter injson.dumps().
Example: Pretty Print JSON
import json# Python objectdata = { "name": "John", "age": 30, "city": "New York"}# Pretty print the JSON stringjson_data = json.dumps(data, indent=4)print(json_data)Output:
{ "name": "John", "age": 30, "city": "New York"}Sorting Keys in JSON: You can also sort the keys in JSON output using the
sort_keysparameter injson.dumps().
Example: Sort Keys in JSON
import json# Python objectdata = { "name": "John", "age": 30, "city": "New York"}# Sort the keys in the JSON stringjson_data = json.dumps(data, indent=4, sort_keys=True)print(json_data)Output:
{ "age": 30, "city": "New York", "name": "John"}JSON and Python Data Types
Python supports a limited set of data types that can be converted to and from JSON:
Python to JSON:
dict-> JSON objectlist,tuple-> JSON arraystr-> JSON stringint,float-> JSON numberTrue-> JSONtrueFalse-> JSONfalseNone-> JSONnull
JSON to Python:
JSON objects -> Python
dictJSON arrays -> Python
listJSON strings -> Python
strJSON numbers -> Python
intorfloatJSON
true-> PythonTrueJSON
false-> PythonFalseJSON
null-> PythonNone
Example: Converting Complex Python Data Structure to JSON
import json# Python object (nested dictionary and list)data = { "name": "John", "age": 30, "is_student": False, "courses": ["Math", "Science"], "address": { "city": "New York", "postal_code": "10001" }}# Convert to JSONjson_data = json.dumps(data, indent=4)print(json_data)Output:
{ "name": "John", "age": 30, "is_student": false, "courses": [ "Math", "Science" ], "address": { "city": "New York", "postal_code": "10001" }}Conclusion
Working with JSON in Python is easy thanks to the built-in json module. Whether you are reading data from an API, writing it to a file, or pretty-printing it for readability, Python provides simple methods for converting between Python objects and JSON.
Use
json.dumps()to convert Python objects to JSON.Use
json.loads()to convert JSON strings to Python objects.Use
json.dump()andjson.load()for working with JSON files.Use parameters like
indentandsort_keysto format JSON output.
If you have any more questions or need further examples, feel free to ask!