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 !

Key Summary

The article from InApps.net provides a beginner-friendly guide to using JSON in Python, leveraging the built-in json library to handle data storage and transfer. JSON, with its key:value pair structure, is widely used for APIs and config files, making it a valuable tool in Python for interoperability with other systems. Key points include:

  • Why Use JSON in Python:
    • JSON is easy to understand, supports primitive types (strings, numbers) and complex structures (nested lists, tuples, objects).
    • Commonly used for data exchange in APIs, config files, and other systems, enhancing Python’s utility.
  • Prerequisites:
    • Python installed (demonstrated on Linux, but applicable to macOS/Windows).
    • A text editor (e.g., nano).
  • Basic Example: Hello, World!:
    • Create hello-world.py:
      python
      CollapseWrapRun
      Copy

import json

sample_json = ‘{“message”: “Hello, World!”}’

data = json.loads(sample_json)

  • print(data[‘message’])
  • Run with python3 hello-world.py to output: Hello, World!
  • Uses json.loads() to parse JSON string into a Python dictionary.
  • Using JSON as a Dictionary:
    • Create dict.py to build and format a JSON dictionary:
      python
      CollapseWrapRun
      Copy

import json

my_dictionary = {

   “name”: “Jack”,

   “age”: 30,

   “city”: “New York”

}

unformatted_json = json.dumps(my_dictionary)

print(unformatted_json)

formatted_json = json.dumps(my_dictionary, indent=4, separators=(“,”, “: “), sort_keys=True)

  • print(formatted_json)
  • Run with python3 dict.py to output:
    • Unformatted: {“name”: “Jack”, “age”: 30, “city”: “New York”}
    • Formatted:
      json
      CollapseWrap
      Copy

{

   “age”: 30,

   “city”: “New York”,

   “name”: “Jack”

  • }
  • Uses json.dumps() to serialize dictionary to JSON string; indent, separators, and sort_keys improve readability.
  • Reading JSON from a File:
    • Create data.json with employee data:
      json
      CollapseWrap
      Copy

[

   {

       “name”: “Jack”,

       “age”: 30,

       “city”: “New York”

   },

   {

       “name”: “Jill”,

       “age”: 25,

       “city”: “Los Angeles”

   }

  • ]
  • Create read_data.py to read and process the file:
    python
    CollapseWrapRun
    Copy

import json

# Open JSON file

with open(‘data.json’) as file:

   # Load JSON data into Python object

   data = json.load(file)

# Iterate over the list of employees

for employee in data:

   print(f”Name: {employee[‘name’]})

   print(f”Age: {employee[‘age’]})

   print(f”City: {employee[‘city’]})

  •    print(“-“ * 20)
  • Run with python3 read_data.py to output:
    text
    CollapseWrap
    Copy

Name: Jack

Age: 30

City: New York

——————–

Name: Jill

Age: 25

City: Los Angeles

  • ——————–
  • Uses json.load() to read JSON file directly into a Python object.
  • Key Takeaways:
    • Python’s json library simplifies working with JSON data, treating it like dictionaries.
    • Functions like loads(), dumps(), load() enable parsing, serializing, and file operations.
    • JSON’s versatility in Python supports diverse applications, from API integration to data storage.
Read More:   The Who, What and Why of Service Mesh – InApps 2022

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:

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:

Finally, we print the information we’ve stored in data with the line:

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.

Read More:   6 Talks That Developers Will Be Excited to See at Oktane21 – InApps Technology 2022

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:

Next, we’ll use the dumps function from JSON on our my_dictionary object with the line:

Finally, we’ll print our JSON data in an unformatted fashion with the line:

Our entire script looks like this:

Save and close the file. Run it with:

python3 dict.py

The output of this app will look something like this:

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:

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:

Save and close the file. If you run the new script with:

python3 dict.py

The output should look like this:

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:

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):

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:

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

Rate this post
As a Senior Tech Enthusiast, I bring a decade of experience to the realm of tech writing, blending deep industry knowledge with a passion for storytelling. With expertise in software development to emerging tech trends like AI and IoT—my articles not only inform but also inspire. My journey in tech writing has been marked by a commitment to accuracy, clarity, and engaging storytelling, making me a trusted voice in the tech community.

Let’s create the next big thing together!

Coming together is a beginning. Keeping together is progress. Working together is success.

Let’s talk

Get a custom Proposal

Please fill in your information and your need to get a suitable solution.

    You need to enter your email to download

      Success. Downloading...