Encoding and Decoding JSON
Updated onbyAlan Morel
Table of Contents
JSON stands for JavaScript Object Notation and it is one of the most popular data formats to store and transfer data between two points. Python has a built-in module called json
that we can use to work with JSON.
Parsing JSON
We can parse a string of JSON into a Python dictionary using the loads()
function in the json
module:
PYTHONimport json
raw_json = '{ "name": "Timmy Turner", "age": 10, "show": "The Fairly OddParents"}'
parsed = json.loads(raw_json)
print(parsed)
JSON{'name': 'Timmy Turner', 'age': 10, 'show': 'The Fairly OddParents'}
While it looks the same as the input, because it is a dictionary, you can access it like you would any dictionary:
PYTHONimport json
raw_json = '{ "name": "Timmy Turner", "age": 10, "show": "The Fairly OddParents"}'
parsed = json.loads(raw_json)
print(parsed["name"])
print(parsed["age"])
print(parsed["show"])
BASHTimmy Turner
10
The Fairly OddParents
Converting to JSON
You can do the reverse and convert a Python object into a string of JSON using the dumps()
function:
PYTHONimport json
obj = {
"name": "Timmy Turner",
"age": 10,
"show": "The Fairly OddParents"
}
converted = json.dumps(obj)
print(converted)
JSON{"name": "Timmy Turner", "age": 10, "show": "The Fairly OddParents"}
Formatting JSON
When you are outputting to JSON, you can pass optional parameters to the dumps()
function to format the output for us.
Here's how to indent the string to make it more readable:
PYTHONimport json
obj = {
"name": "Timmy Turner",
"age": 10,
"show": "The Fairly OddParents"
}
converted = json.dumps(obj, indent=4)
print(converted)
JSON{
"name": "Timmy Turner",
"age": 10,
"show": "The Fairly OddParents"
}
Resources
Leave us a message!
×
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js