I am studying with reference to O'Reilly Japan's "Data Visualization Beginning with Python and JavaScript".
module
# coding:UTF-8
import json
import csv
#Load JSON file
json_dict = json.load(open('data/players.json', 'r'))
#Extraction of list of dict
target_dicts = json_dict['players']
with open('data/players.csv', 'w') as f:
#Dialect registration
csv.register_dialect('dialect01', doublequote=True, quoting=csv.QUOTE_ALL)
#DictWriter creation
writer = csv.DictWriter(f, fieldnames=target_dicts[0].keys(), dialect='dialect01')
#Write to CSV
writer.writeheader()
for target_dict in target_dicts:
writer.writerow(target_dict)
# coding:UTF-8
import json
import csv
json_list = []
json_data = {}
#Load CSV file
with open('data/players.csv', 'r') as f:
#Creating a list of dict
for line in csv.DictReader(f):
json_list.append(line)
json_data["players"] = json_list
with open('data/players.json', 'w') as f:
#Write to JSON
json.dump(json_data, f)
{
"players": [
{
"id": "0001",
"name": "Nishikawa Haruki",
"position": "center fielder"
},
{
"id": "0002",
"name": "Matsumoto Go",
"position": "right fielder"
},
{
"id": "0003",
"name": "Brandon J. Laird",
"position": "third baseman"
} ,
{
"id": "0004",
"name": "Nakata Sho",
"position": "first baseman"
}
]
}
"id","name","position"
"0001","Nishikawa Haruki","center fielder"
"0002","Matsumoto Go","right fielder"
"0003","Brandon J. Laird","third baseman"
"0004","Nakata Sho","first baseman"
Data visualization starting with Python and JavaScript https://www.oreilly.co.jp/books/9784873118086/
14.1. csv — Read and write CSV files https://docs.python.jp/3.3/library/csv.html
19.2. json — JSON encoder and decoder https://docs.python.jp/3.3/library/json.html
Recommended Posts