JSON operations with Python
What will we learn?
- We will learn JSON operations with Python
Requirements:
- Notepad+
- Python
- JSON
- Linux operating systems
Difficulty Level:
- Normal Level
Let's Start the Course :
It is a lightweight data interchange format that is independent of the JSON (JavaScript Object Notation) programming language. It takes up much less space than XML. It's easy for people to read and write. Every programming is very easy to interpret in the language. Supports the following data types.
- İnteger
- String
- Boolean
- Array
- Object
- Null
With the json module installed in Python, we can process it very easily.
ENCODE
We may want to convert the data we have created in Python to a JSON type to transfer to other places. With the 'json.dumps ()' function we can do this very easily.
First, let's include the module in the project:
import json
Then we will put the data in the json file in a format appropriate to the python writing rules.
As an example, I created a structure that stores car models.
cars = {
"audi" : {
"A3" : {
"color_options" : {"black", "white", "Grey"} ,
"Fuel" : " Gasoline"
},
"A7" : {
"color_options" : {"black", "white",} ,
"Fuel" : " Diesel"
}
},
"jeep" : {
"CHEROKEE" : {
"color_options" : {"black""} ,
"Fuel" : " Gasoline"
},
"WRANGER" : {
"color_options" : {"black", "white",} ,
"Fuel" : " Gasoline"
}
}
}
Now convert this data to JSON format easily with json.dumps () function.
json_data = json.dumps(cars)
We can see the JSON implementation by printing the json_data variable. Syntactically, PYTHON is very similar.
DECODE:
We need to translate this data into python format in order to easily use JSON data generated earlier.
We will use thejson.loads () function for this.
We include the module in the project.
import json
Let's create a simple json data and assign a variable.
json_data = """{"name" : "Utopian" , "LastName": "Kingmaggot"}"""
We can also extract the Json data in a variable from a file or from a site.
Now we can convert the data into PYTHON type and print it on the screen one by one
datas = json.load (json_data)
print(datas["name"])
print(datas["LastName"])
Output :
Utopian
Kingmaggot
For the rest of the article, follow our series.
Series :
1 - JSON operations with Python #1
Posted on Utopian.io - Rewarding Open Source Contributors
Your contribution cannot be approved because it does not follow the Utopian Rules.
This is too simple of a tutorial and does not cover enough information or functionalities in dealing with JSON via Python.
Please expand your tutorials in the future to cover more complex and detailed aspects
You can contact us on Discord.
[utopian-moderator]