Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Python JSON?

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What is Python JSON? I believe many inexperienced people are at a loss about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Do you know how to transfer data from online API or store various data on your local computer? You have immersed yourself in a way of JSON, where JSON stands for JavaScript Object Notation. It is a well-known popular data format for representing semi-structured data. Let's learn more about Python JSON.

Introduction to Python JSON:

JSON stands for JAVA trumpet script objectn flotation is a way to store information in an organized and easy way. When exchanging data between the browser and the server, the data must be in text form.

If you want to know if it is JavaScript? So the answer is no. It is a script of text that stores and transmits data in human and machine-readable formats. It is a small lightweight data format inspired by JavaScript and is usually used in text or string format. JSON packets are almost equivalent to python dictionaries. Now, you must want to know.

How to read JSON files in Python?

The answer to the question is that you must import the JSON module, which typically converts the Python data type to an JSON string file. It consists of JSON functions that read and write directly from the JSON file. Python has a built-in JSON package and is part of the standard library, so you don't need to install it.

Example:

Import json

Now that you know JSON in Python, let's take a closer look at Parsing.

Parsing:

The JSON library can parse JSON from a string or file. It can also parse JSON into Python dictionaries or lists, and vice versa. Parsing is usually divided into two phases:

Convert from JSON to Python

Convert from Python to JSON

Let's have a better understanding of these two stages.

Convert from JSON to Python:

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

Example:

Import jsonpeople_string ='{"people": [{"emp_name": "John smith", "emp_no.": "924367-567-23", "emp_email": ["johnsmith@dummyemail.com"], "has_license": "false"}, {"emp_name": "harshit kant", "emp_number": "560555-5153", "emp_email": "null" "has_license": "true"}]}''data = json.loads (people_string) print (data)

Output:

As you can see from the output above, it has printed the Python dictionary. Let's print the data types for better understanding.

Example:

Import jsonpeople_string ='{"people": [{"emp_name": "John smith", "emp_no.": "924367-567-23", "emp_email": ["johnsmith@dummyemail.com"], "has_license": "false"}, {"emp_name": "harshit kant", "emp_number": "560555-5153", "emp_email": "null" "has_license": "true"}}''data = json.loads (people_string) print (type (data)) # prints the datatype

Output:

Now that you are familiar with one transformation, let's look at another type of transformation in the second phase.

Convert from Python to JSON:

By using json.dumps (). The following example converts a Python object to a JSON string:

Example:

Import jsonpeople_string ='{"people": [{"emp_name": "John smith", "emp_no.": "924367-567-23", "emp_email": ["johnsmith@dummyemail.com"], "has_license": "false"}, {"emp_name": "harshit kant", "emp_no.": "560555-5153", "emp_email": "null" "has_license": "true"}}''data = json.loads (people_string) new_string = json.dumps (data) print (new_string)

Output:

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

Let's move on and see how Pandas parses JSON.

Panda parsing JSON:

You can parse JSON strings to pandas Dataframe by following these steps:

The following general structure can be used to load JSON strings into DataFrame

Import pandas as pd pd.read_json (r'Path where you saved the JSON fileFile Name.json')

Prepare the JSON string.

Create a JSON file, nobel_prize.json, that we are using.

Load the JSON file into pandas DataFrame.

The code implemented below loads my JSON file into DataFrame.

Import pandas as pdimport json with open (ringing Cbureau UsersHarshitzKantDesktopnobel.prize.json') as f: data = json.load (f) print (data) df = pd.DataFrame print (df)

Output:

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

JSON serialization [Encoding]:

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

The following table is a table that describes converting Python data types to their respective JSON types.

The main points to remember:

Dump ()-converts data to a JSON file

Dumps ()-converts data to JSON strings

Load ()-converts a JSON file to a Python object

Loads ()-converts an object of a JSON string to a Python object

Beautiful printing:

Pretty Printing is responsible for aligning the code and making it human-readable. Let's look at the following example, where I passed two parameters, 'sort_keys', which always return Boolean truth values and' indent' spaces.

Example:

Import jsonpeople_string ='{"people": [{"emp_name": "John smith", "emp_no.": "924367-567-23", "emp_email": ["johnsmith@dummyemail.com"], "has_license": "false"}, {"emp_name": "harshit kant", "emp_no.": "560555-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)

Output:

Continuing with the Python JSON tutorial, let's learn about deserialization of JSON.

Deserialization of JSON [Decode]:

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

The following table is a table that describes converting the JSON data type to its corresponding Python type.

Continue with the "Python JSON" tutorial. I'll show you a real-time example of serialization and deserialization at the same time from a coding perspective.

Coding demonstration:

In this coding demonstration, I will use the JSON dataset given here, called the Nobel Prize. You will learn how to serialize and deserialize through JSON files.

Example (serialization of JSON datasets): 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)

Output:

The Python code has been successfully compiled and a new file "new_nobel_prize.json" has been created that will dump the data from the existing file "nobel_prize.json".

Example (deserialization of JSON datasets): 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'])

Output:

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

After reading the above, have you mastered what is the method of Python JSON? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report