Abstract: Do you know how to transfer data from an online API or store various data to a local computer? You’ve immersed yourself in one way: JSON, which stands for Java Script Object Notation. It is a well-known popular data format for representing semi-structured data. Let’s take a closer look at Python JSON.

Share this article from huawei cloud community “from scratch to learn python | what python JSON is and how to implement?” , original author: Yuchuan.

Do you know how to transfer data from an online API or store various data to a local computer? One way you’ve immersed yourself is in JSON, which stands for Java Script ObjectNotation. It is a well-known popular data format for representing semi-structured data. Let’s take a closer look at Python JSON.

This article will discuss the following aspects:

  • Python JSON profile

  • How do I read JSON files in Python

  • Parsing.

  • Convert from Python to JSON

  • Convert from JSON to Python

  • Panda Parse JSON

  • JSON serialization [encoding]

  • Beautiful printing

  • JSON deserialization [decode]

  • Coding demonstration

Python JSON

JSON stands for JAVA Trumpet Scriptobjectn Flotation is a way to store information in an organized and easy way. When data is exchanged between the browser and the server, it must be in text form.

If you want to know if it’s JavaScript? So the answer is ** no. ** It is a script composed of text for storing and transferring data in human – and machine-readable formats. It is a small, lightweight data format inspired by JavaScript that is typically used as text or string format. JSON packets are almost equivalent to Python dictionaries. Now, you must be wondering.

How do I read JSON files in Python?

The answer is that you must import JSON modules, which typically convert Python data types into JSON string files. It consists of JSON functions that read and write directly from JSON files. Python comes with a built-in JSON package and is part of the standard library, so you don’t need to install it.

Example:

import json
Copy the code

Now that you’ve looked at JSON in Python, let’s dive into Parsing a bit more.

Resolution:

JSON libraries can parse JSON from strings or files. It can also parse JSON into a Python dictionary or list, and vice versa. Parsing is usually divided into two phases:

1. Convert from JSON to Python

2. Convert from Python to JSON

Let’s understand these two stages better.

Converting from JSON to Python:

You can convert JSON strings to Python json.loads() using the following method:

Example:

import jsonpeople_string = '''{"people":[{"emp_name": "John smith","emp_no.": "924367-567-23","emp_email": ["[email protected]"],"has_license": "false"},{"emp_name": "harshit kant","emp_number": "560-555-5153","emp_email": "null","has_license": "true"}]}'''data = json.loads(people_string)print(data)
Copy the code

Output:

As you can see from the output above, it has printed the Python dictionary. Let’s print the data type to get a better understanding.

Example:

import jsonpeople_string = '''{"people":[{"emp_name": "John smith","emp_no.": "924367-567-23","emp_email": ["[email protected]"],"has_license": "false"},{"emp_name": "harshit kant","emp_number": "560-555-5153","emp_email": "null","has_license": "true"}]}'''data = json.loads(people_string)print(type(data))  #prints the datatype
Copy the code

Output:

<class’dict’>

Now that you’re familiar with one transformation, let’s look at another transformation type in phase 2.

Converting from Python to JSON:

Python objects can be converted to JSON strings using the example given below with json.dumps() :

Example:

import jsonpeople_string = '''{"people":[{"emp_name": "John smith","emp_no.": "924367-567-23","emp_email": ["[email protected]"],"has_license": "false"},{"emp_name": "harshit kant","emp_no.": "560-555-5153","emp_email": "null","has_license": "true"}]}'''data = json.loads(people_string)new_string = json.dumps(data)print(new_string)
Copy the code

Output:

The output will be of the JSON string type. I have demonstrated data types in a JSON-to-Python conversion, and will follow the same process for printing data types.

Let’s go ahead and see how Pandas parses JSON.

Panda parse JSON:

To parse the JSON string to pandas Dataframe, do the following:

  • The following generic structure can be used to load JSON strings into a DataFrame

    import pandas as pd pd.read_json(r’Path where you saved the JSON fileFile Name.json’

  • Prepare the JSON string.

  • Create the JSON file we are using, nobel_prize. JSON.

  • Load the JSON file into the PANDAS DataFrame.

The code implemented below loads my JSON file into the DataFrame.

import pandas as pdimport json with open(r'C:UsersHarshit_KantDesktopnobel.prize.json') as f:   data = json.load(f)print (data) df = pd.DataFrame print(df)
Copy the code

Output:

Moving on, let’s see how to serialize JSON in Python.

JSON serialization [encoding] :

Serializing JSON simply means that you are encoding JSON. It converts a given Python data structure (ex: dict) into its valid JSON object. To process data flows in files, the JSON library in Python uses the **dump () ** and **dumps () ** methods, which transform and make it easy to write data to files.

The following table illustrates converting Python data types to their respective JSON types.

Key points to remember:

Dump () – Converts data to JSON files

Dumps () – Converts data to JSON strings

Load () – Converts JSON files into Python objects

Loads () – Converts JSON string objects into Python objects

Beautiful printing:

Pretty Printing is responsible for code alignment and making it in a human-readable format. Let’s look at the following example, where I pass two arguments ‘sort_keys’, which always return a Boolean True and ‘indent’ space.

Example:

import jsonpeople_string = '''{"people":[{  "emp_name": "John smith",  "emp_no.": "924367-567-23",  "emp_email": ["[email protected]"],  "has_license": "false"},{  "emp_name": "harshit kant",  "emp_no.": "560-555-5153",  "emp_email": "null",  "has_license": "true"}]}''' data = json.loads(people_string)new_string = json.dumps(data, sort_keys=True, indent=3)print(new_string)
Copy the code

Output:

Continuing with the Python JSON tutorial, let’s look at deserialization of JSON.

JSON deserialization [Decode] :

Deserialization of JSON is the exact opposite of serialization, that is, it means you are decoding JSON. It converts the given JSON string into a Python object using the load () and load () methods that perform the transformation.

The following table illustrates converting JSON data types to their corresponding Python types.

Continue with the PythonJSON tutorial. I’ll show you a live example of both serialization and deserialization from a coding perspective.

Coding demo:

In this coding demo, I’ll use the JSON data set presented here, called “Nobel Prize.” You’ll learn how to serialize and deserialize from JSON files.

Example (serialization of JSON data set) :

import json with open('nobel_prize.json.html') as f:    data = json.load(f) with open('new_nobel_prize.json.html') as f:    json.dump(data,f,indent=2)
Copy the code

Output:

The Python code compiled successfully, and a new file “new_nobel_prize. Json” was created to dump the data from the existing file “nobel_prize.

Example (deserialization of JSON data set) :

import json with open('nobel_prize.json.html') as f:data = json.load(f) for nobel_prize in data['prizes']:print(nobel_prize['year'],nobel_prize['category'])
Copy the code

Output:

This code snippet shows the changes from the JSON file to its corresponding Python object.

Hopefully, all the concepts related to JSON parsing, serialization, and deserialization are clear to you.

Click to follow, the first time to learn about Huawei cloud fresh technology ~