Understanding JSON and Its Use in Python
When processing data in Python, you often find yourself dealing with JSON format data.
JSON (JavaScript Object Notation)
is a widely used data format for exchanging and storing data, characterized by the following features:
-
Concise and Readable: It's a text format that's easy for both humans and machines to understand.
-
Key-Value Pairs: Data is expressed in pairs of names and values.
-
Standard Library Support: Most programming languages provide libraries to handle JSON.
JSON consists of a set of key-value pairs enclosed by curly braces {}
, formatted as below:
{ "name": "CodeBuddy", "age": 30, "city": "New York" }
JSON also supports array format enclosed by square brackets []
.
[ { "name": "CodeBuddy", "age": 30, "city": "New York" }, { "name": "JohnCode", "age": 25, "city": "Los Angeles" } ]
JSON values can be numbers, strings, booleans (true/false), arrays, objects, or null.
Parsing and Utilizing JSON
In Python, you can use the built-in json
module to convert JSON strings into Python objects using json.loads
, or convert Python objects into JSON strings using json.dumps
.
json.loads
: Converting JSON to a Python Object
-
Converts a JSON string into a Python data structure (e.g., dictionary).
-
Commonly used to handle JSON data received from API responses.
import json # Import the built-in json module json_string = '{"name": "JohnCode", "age": 30, "city": "New York"}' # Convert JSON string to Python object data = json.loads(json_string) print(data)
json.dumps
: Converting an Object to JSON
-
Converts an object (dictionary, list, etc.) into a JSON string.
-
Used to send data in JSON format to an API.
import json # Import the built-in json module data = { "name": "JohnCode", "age": 30, "city": "New York" } # Convert Python object to JSON string json_string = json.dumps(data) print(json_string)
Practice
Click the Run Code
button on the right and try modifying the code to see your results!
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result