Read JSON with Python and output as CSV

Purpose

It is a program to read a JSON file, aggregate the contents, and output it as CSV. Since the aggregated content changes depending on the usage, I am only making a place to read and output JSON.

What to do

--Display a file selection dialog --Read JSON file --Aggregate and output as CSV

Display a file selection dialog

Use tkinter to display a GUI (file selection dialog). As soon as you run it, a file selection dialog will appear, allowing you to select only JSON files.

#Module import
import os, tkinter, tkinter.filedialog

#Display file selection dialog
root = tkinter.Tk()
root.withdraw()

#Make only json files selectable
fTyp = [("","*.json")]
iDir = os.path.abspath(os.path.dirname(__file__))
file = tkinter.filedialog.askopenfilename(filetypes = fTyp, initialdir = iDir)

#Check the path of the selected file
print(file)

Read JSON file

When you can select the file, check the contents of the JSON file. Add the json library to read and handle files.

#Module import
import os, json, tkinter, tkinter.filedialog

#Display file selection dialog
root = tkinter.Tk()
root.withdraw()

#Make only json files selectable
fTyp = [("","*.json")]
iDir = os.path.abspath(os.path.dirname(__file__))
file = tkinter.filedialog.askopenfilename(filetypes = fTyp, initialdir = iDir)

#Read json file
json_open = open(file, 'r', encoding="utf-8")
json_load = json.load(json_open)

#Check the contents of the json file
print(json_load[0])

CSV output

Now that we have read the JSON file, let's make it output to CSV.

#Module import
import os, json, csv, tkinter, tkinter.filedialog

#Display file selection dialog
root = tkinter.Tk()
root.withdraw()

#Make only json files selectable
fTyp = [("","*.json")]
iDir = os.path.abspath(os.path.dirname(__file__))

#Get file information
file = tkinter.filedialog.askopenfilename(filetypes = fTyp, initialdir = iDir)

#Read json file
json_open = open(file, 'r', encoding='utf-8')
json_load = json.load(json_open)

#Set the folder and file name to output CSV (same name in the same location as the read JSON file)
folder_file = os.path.split(file)
folder = folder_file[0] #Get folder path
file_name = file.rsplit('/', 1)[1][0:-5] #Get the file name
csv_file_path = folder + '/' + file_name + '.csv'

#Create CSV file (create new if it does not exist)
if not os.path.isfile(csv_file_path):
  open(csv_file_path, 'x', encoding='utf-8')

#Read CSV in overwrite mode
csv_file = open(csv_file_path, 'w', encoding='utf-8')

#Write settings to CSV
w = csv.writer(csv_file, lineterminator='\n')

#Write and write the aggregation process according to the contents of JSON
#w.writerow(['AAA','test','111'])← In the case of one line at a time
w.writerows([['AAA','Test','111'], ['BBB','tEst','222'], ['CCC','teSt','333'], ['DDD','tesT','444']])

csv_file.close()

that's all. After that, let's add up as you like.

reference

-Python: How to select a processing file from GUI -Read JSON with Python -Python: Read JSON data from web API -Output to csv file with Python -[Python] Write to csv file with Python -The story that the "cp932" file could not be opened when reading the Json file with Python -About reading and writing (overwriting, adding) files -Set the line feed code of the file output by the Python csv module to LF

Recommended Posts

Read JSON with Python and output as CSV
Read json file with Python, format it, and output json
Extract bigquery dataset and table list with python and output as CSV
[Python3] Read and write with datetime isoformat with json
Read csv with python pandas
Read json data with python
Read CSV file with Python and convert it to DataFrame as it is
Output to csv file with Python
JSON encoding and decoding with python
Reading and writing CSV with Python
[Python] Read the csv file and display the figure with matplotlib
Data input / output in Python (CSV, JSON)
Read CSV file with python (Download & parse CSV file)
Read and write csv files with numpy
Reading and writing JSON files with Python
Read Python csv and export to txt
Read and write JSON files in Python
Read CSV and analyze with Pandas and Seaborn
How to read a CSV file with Python 2/3
Csv output from Google search with [Python]! 【Easy】
[Python] Use JSON with Python
Read Python csv data with Pandas ⇒ Graph with Matplotlib
Extract the TOP command result with USER and output it as CSV
Reading and writing CSV and JSON files in Python
python input and output
Send and receive image data as JSON over the network with Python
Csv tinkering with python
Make JSON into CSV with Python from Splunk
Read Python csv file
Example of reading and writing CSV with Python
Procedure to load MNIST with python and output to png
[Part.3] Crawling with Python! It's JSON rather than CSV! ??
Read and analyze arff format dataset with python scipy.io
Parse and visualize JSON (Web application ⑤ with Python + Flask)
How to convert JSON file to CSV file with Python Pandas
Output log in JSON format with Python standard logging
Read and write files with Slackbot ~ Bot development with Python ~
[Python-pptx] Output PowerPoint font information to csv with python
Programming with Python and Tkinter
Read and write csv file
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
POST json with Python3 script
Try Python output with Haxe 3.2
Write to csv with Python
python with pyenv and venv
Format json with Vim (with python)
Download csv file with python
Read Fortran output in python
Works with Python and R
[Python] Read Japanese csv with pandas without garbled characters (and extract columns written in Japanese)
Easily write JSON and Python dataclass conversions with quicktype and dacite
Sort and output the elements in the list as elements and multiples in Python.
Sample of HTTP GET and JSON parsing with python of pepper
Precautions when inputting from CSV with Python and outputting to json to make it an exe
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
Grayscale image and save as csv
Neural network with OpenCV 3 and Python 3