[Introduction to Python] How to handle JSON format data

Reference site: [Introduction to Python] How to handle JSON format data

[Introduction to Python] How to handle JSON format data

When exchanging data with a web application, data may be exchanged in the format of "JSON". JSON is used in various languages such as C and JAVA, and of course Python can handle it as well. This time, I'll cover the basics of how to work with JSON in Python.

table of contents 1 [What is JSON](## What is JSON) 2 [Handle JSON](## Handle JSON) 2.1 [Read JSON file](## Read JSON file) 2.2 [Convert JSON](## Convert JSON) 2.3 [Write JSON](## Write JSON)

What is JSON

First of all, I will explain what kind of format JSON is. JSON is an abbreviation for "JavaScript Object Notation" and can be said to be a "data format based on the notation of the JavaScript language". However, the notation is just JavaScript-based and can be used in many other languages. In JSON, a number and a key pair that is the name of that number are paired with a colon, separated by commas, and enclosed in curly braces.

{
 "book1":{
"title": "Python Beginners",
 "year": 2005 ,
"page": 399
},
"book2":{
 "title": "Python Developers",
 "year": 2006 ,
"page": 650
 }
}

Handle JSON

Now let's see how to actually handle JSON-formatted data in Python.

Read JSON file

To work with a JSON file, you first need to read the data from the JSON file. The procedure to read the JSON file is (1) Open the JSON file (2) Read the opened file as JSON There are two steps. Specifically, it is described as follows.

import json #Must be required
Variable 1= open(‘The path of the JSON file to read’, ‘r’) #Here is(1)
Variable 2= json.load(Variable 1) #Here is(2)

In order to use JSON related functions, you first need to import the json module. Don't forget. Then open the JSON file as a read file. This is the same as a normal file operation. Then save the loaded JSON file as a JSON object using the load function. You have now loaded the JSON.

JSON conversion

When you load a JSON file with the load function, it is saved as a dictionary for ease of use in Python. The dictionary type is convenient because you can easily retrieve elements, but sometimes you want to treat it as a JSON-formatted character string. In that case, let's convert from dictionary type to JSON format string. Use the dumps function to convert a dictionary to a JSON-formatted string.

import json
Variable 1= json.dumps(Variable 2) #Variable 2 は辞書型
dumps is also a function of the json module, so import the json module before using it.
dumps is a function that takes a dictionary type as an argument, converts it to a string and returns it.
import json
f = open('test.json', 'r')
json_dict = json.load(f)
print('json_dict:{}'.format(type(json_dict)))
print('-----Convert from dictionary type to JSON format string-----')
json_str = json.dumps(json_dict)
print('json_str:{}'.format(type(json_str)))

Execution result

json_dict: —– Convert from dictionary type to JSON format string —– json_str:

On the contrary, you can also convert a JSON-formatted string to a dictionary type. Use the loads function of the json module for conversion.

import json
-Since it is the same as the above example, it is omitted.
json_dict2 = json.loads(json_str)
print(‘json_dict2:{}’.format(type(json_dict2)))

Execution result

json_dict: —– Convert from dictionary type to JSON format string —– json_str: —– Convert JSON format string to dictionary type —– json_dict2: Write JSON

JSON data handled by Python can be written to a file. Writing to a file Only use the dump function of the json module. Please note that it is not dumps.

import json
Variable 1= open(‘Writing file path’, ‘w’) #Open the file to write
json.dump(Variable 2,Variable 1) #Variable 2 は辞書型

dump takes the dictionary type variable you want to write and the file to write to as arguments. You can write a JSON-formatted string with the write function like a normal file write, but if you want to write a dictionary type, this method does not need to be converted one by one, so it is easy. So, as a summary, let's see the flow of the list that reads the following json file, converts it to a character string, makes it dictionary type again, and writes it to another json file.

test.json

{
 "book1":{
"title":"Python Beginners",
"year": 2005 ,
"page": 399
},
"book2":{
 "title": "Python Developers",
 "year": 2006 ,
"page": 650
}
}
import json
#Read JSON file
f = open('test.json', 'r')
json_dict = json.load(f)
print('json_dict:{}'.format(type(json_dict)))
#JSON data conversion
print('-----Convert from dictionary type to JSON format string-----')
json_str = json.dumps(json_dict)
print('json_str:{}'.format(type(json_str)))
print('-----Convert JSON format string to dictionary type-----')
json_dict2 = json.loads(json_str)
print('json_dict2:{}'.format(type(json_dict2)))
#Writing JSON data
f2 = open('test2.json', 'w')
json.dump(json_dict2, f2)

Execution result

json_dict: —– Convert from dictionary type to JSON format string —– json_str: —– Convert JSON format string to dictionary type —– json_dict2: test2.json {“book2″: {“year”: 2006, “title”: “Python Developers”, “page”: 650}, “book1″: {“year”: 2005, “title”: “Python Beginners”, “page”: 399}}

Recommended Posts

[Introduction to Python] How to handle JSON format data
[Introduction to Python] How to parse JSON
How to handle data frames
How to handle JSON in Ruby, Python, JavaScript, PHP
[Python] How to FFT mp3 data
Handle NetCDF format data in Python
How to handle Japanese in Python
[Introduction to Python] How to get data with the listdir function
[Introduction to Python] How to use class in Python?
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
Convert Excel data to JSON with python
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
How to use "deque" for Python data
How to handle time series data (implementation)
[Introduction to Data Scientists] Basics of Python ♬
How to install Python
[Python] How to change the date format (display format)
Just add the python array to the json data
How to create a JSON file in Python
How to install python
[Python] How to read data from CIFAR-10 and CIFAR-100
Introduction to Python language
How to read JSON
How to generate a Python object from JSON
Introduction to OpenCV (python)-(2)
How to handle Linux commands well from Python
How to make Substance Painter Python plugin (Introduction)
[Introduction to Python] How to write a character string with the format function
Convert json format data to txt (using yolo)
Data cleaning How to handle missing and outliers
[Python] How to handle Japanese characters with openCV
How to handle datetime type in python sqlite3
[Introduction to Python] How to get the index of data with a for statement
[For beginners] How to study Python3 data analysis exam
[Introduction to Python] How to iterate with the range function?
How to convert JSON file to CSV file with Python Pandas
Convert / return class object to JSON format in Python
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Introduction to Python] How to stop the loop using break?
How to convert Json file to CSV format or EXCEL format
Try writing JSON format data to object storage Cloudian/S3
[Introduction to Python] How to write repetitive statements using for statements
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
Handle Ambient data in Python
[2020.8 latest] How to install Python
Easily format JSON in Python
How to install Python [Windows]
Introduction to Python Django (2) Win
python3: How to use bottle (2)
[Python] How to use list 1
How to update Python Tkinter to 8.6
How to use Python argparse
Introduction to serial communication [Python]
Python: How to use pydub
[Python] How to use checkio
How to run Notepad ++ Python
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)