- Home
- >
- Software Development
- >
- How to Use JSON in Python – InApps Technology 2022
How to Use JSON in Python – InApps Technology is an article under the topic Software Development Many of you are most interested in today !! Today, let’s InApps.net learn How to Use JSON in Python – InApps Technology in today’s post !
Read more about How to Use JSON in Python – InApps Technology at Wikipedia
You can find content about How to Use JSON in Python – InApps Technology from the Wikipedia website
JSON is an outstanding way of storing and transferring data. Recently, I wrote an introduction on how to use JSON, and given we’ve also gone pretty deep down the rabbit hole of Python, I thought it would be a great way to tie this all together by demonstrating how you can leverage the power of JSON within Python.
Python has built-in support for JSON, via a package aptly named JSON, and treats JSON similarly to dictionaries. Within Python, JSON supports primitive types (such as strings and numbers) as well as nested lists, tuples and objects.
But why would you use JSON in an already easy language such as Python?
Simple. JSON is not only easy to comprehend, with its key:value pairs, but it’s also very often used as a common data format for storing and fetching data from APIs and config files. In other words, a lot of other systems, applications and services already use JSON to store and transfer data, so why wouldn’t you want to use it in Python?
With that said, let’s find out how you can work with JSON inside of your Python code.
Hello, World!
Yep, we’re back to our favorite application, Hello world! We’re going to create this easy application using good ol’ Python and JSON.
The first thing we’ll do is create our Python script. Open a terminal window (I’m demonstrating on Linux with Python installed) and create the new file with the command:
nano hello-world.py
To use JSON in your Python code, the first thing we must do is import the JSON library with the entry:
Our next line contains the actual JSON entry and looks like this:
sample_json = ‘{ “name1″:”Hello,”, “name2″:”World!”}’ |
Because we’re using JSON, we have to work with a special function in the json library, called loads. What this will do is load the JSON data from sample_json and assign it to the variable data. This line looks like this:
data = json.loads(sample_json) |
Finally, we print the information we’ve stored in data with the line:
print(f‘{data[“name1”]} {data[“name2”]}’) |
Save and close the file. Run the app with the command:
You should see printed out:
Hello, World!
Simple! Let’s get a bit more complicated. We’ll create a simple Python script that uses JSON as a dictionary and then we’ll see how we can print the data as both unformatted and formatted results.
Create the new script with the command:
nano dict.py
Obviously, the first line will import the JSON library:
Next, we build our dictionary using JSON key:value pairs like so:
my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “my_neighbor”: False } |
Next, we’ll use the dumps function from JSON on our my_dictionary object with the line:
unformatted_json = json.dumps(my_dictionary) |
Finally, we’ll print our JSON data in an unformatted fashion with the line:
Our entire script looks like this:
import json
my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “my_neighbor”: False }
unformatted_json = json.dumps(my_dictionary) print(unformatted_json) |
Save and close the file. Run it with:
python3 dict.py
The output of this app will look something like this:
{“name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “emails”: [{“email”: “[email protected]”, “type”: “work”}], “my_neighbor”: false} |
Instead of printing out unformatted text, we can actually print it out in a more standard JSON format. To do that, we have to first add a section under the my_dictionary section that looks like this:
formatted_json = json.dumps( my_dictionary, indent = 4, separators = (“, “, ” = “), sort_keys = True ) |
What the above section does is use the dumps function from JSON and then formats my_dictionary with indents and double-quote separators and also sorts the output dictionaries by key (with sort_keys = True), all the while assigning the data to the formatted_json variable.
Under that section, we then print the dictionary with the line:
Our entire script looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import json
my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “my_neighbor”: False }
formatted_json = json.dumps( my_dictionary, indent = 4, separators = (“, “, ” = “), sort_keys = True )
print(formatted_json) |
Save and close the file. If you run the new script with:
python3 dict.py
The output should look like this:
{ “company_name” = “InApps Technology”, “emails” = [ { “type” = “work” } ], “job_title” = “Writer”, “my_neighbor” = false, “name” = “Jack Wallen”, “speciality” = “Linux” } |
Read JSON from a File
Let’s say you have a long JSON-formatted file of employee data. That file might be called data.json and look like this:
{ “employee_details”: [ { “employee_name” : “Jack Wallen”, “employee_title” : “writer” }, { “employee_name” : “Olivia Nightingale”, “employee_title” : “editor” } ] } |
We have information for two employees laid out in JSON format.
Now, our Python app (named read_data.py) to read in that data might look something like this (with comments for explanation):
# Import the JSON library import json
# Open our JSON file named data.json f = open(‘data.json’)
# returns JSON object as a dictionary data = json.load(f)
# Iterate through the entire data.json list for i in data[’employee_details’]: print(i)
# Close the data.json file f.close() |
Save and close the file. Run the app with the command:
python3 read_data.py
The output of the app will look something like this:
{’employee_name’: ‘Jack Wallen’, ’employee_email’: ‘[email protected]’, ’employee_title’: ‘writer’} {’employee_name’: ‘Olivia Nightingale’, ’employee_email’: ‘[email protected]’, ’employee_title’: ‘editor’} |
And there you go! You’ve used JSON within a Python application. As you might imagine, the possibilities are limitless with what you can do with this juxtaposition.
Source: InApps.net
Let’s create the next big thing together!
Coming together is a beginning. Keeping together is progress. Working together is success.