Read json file with Python, format it, and output json

The other day, I summarized how to read a json file with PowerShell, perform necessary formatting and output json, but since I tried it with Python, I would like to keep it as a memorandum.

Code done in last PowerShell

First is the json file to read.

data.json


{
    "prefectures": [
        {
            "code": "Tokyo",
            "name": "Tokyo"
        },
        {
            "code": "Osaka",
            "name": "Osaka"
        },
        {
            "code": "Aichi",
            "name": "Aichi"
        },
        {
            "code": "Fukuoka",
            "name": "Fukuoka"
        }
    ],
    "tables": [
        {
            "code": "meeting_room",
            "name": "conference room",
            "field1": "id",
            "field2": "floar",
            "field3": "capacities"
        },
        {
            "code": "parking",
            "name": "Parking Lot",
            "field1": "id",
            "field2": "area",
            "field3": "space_number",
            "field4": "user_name",
            "field5": "car_number",
            "field6": "expire"
        }
    ]
}

What I want to output is a json file for each item of prefectures x tables. In addition, the json adds the area code and area name to each of the table's code and name.

Completed code

Here is the code I tried. I think that the contents of the for sentence on the 17th and 22nd lines can be organized more neatly, so I need to devote myself.

main.py


import os
import sys
import pathlib
import json
import itertools


def json_make():
    """
Output json for region x table type from Json data
    """
    jsonfile = open('data.json', 'r')
    data = json.load(jsonfile)

    prefectures = data['prefectures']
    tables = data['tables']

    for pref, table in itertools.product(prefectures, tables):
        pref_code = pref["code"]
        pref_name = pref["name"]
        result = {}

        for k in table:
            if k == 'code':
                result['code'] = f'{pref_code}_{table[k]}'
            elif k == 'name':
                result['name'] = f'{pref_name}_{table[k]}'
            else:
                result[k] = table[k]

        expfile = open("./results/" + result['code'] + '.json', 'w')
        # ensure_ascii=Avoid Japanese encoding by adding False
        json.dump(result, expfile, indent=4, ensure_ascii=False)


#Do not process if there is no file
if os.path.exists('data.json') is False:
    sys.exit()

#Create if there is no output folder
exp = pathlib.Path('./results')
if exp.exists() is False:
    exp.mkdir()

json_make()

Output result

naoki$ ls -l results
-rw-r--r--  1 naoki  staff  139  4 19 13:16 Aichi_meeting_room.json
-rw-r--r--  1 naoki  staff  214  4 19 13:16 Aichi_parking.json
-rw-r--r--  1 naoki  staff  141  4 19 13:16 Fukuoka_meeting_room.json
-rw-r--r--  1 naoki  staff  216  4 19 13:16 Fukuoka_parking.json
-rw-r--r--  1 naoki  staff  139  4 19 13:16 Osaka_meeting_room.json
-rw-r--r--  1 naoki  staff  214  4 19 13:16 Osaka_parking.json
-rw-r--r--@ 1 naoki  staff  139  4 19 13:16 Tokyo_meeting_room.json
-rw-r--r--  1 naoki  staff  214  4 19 13:16 Tokyo_parking.json

Aichi_meeting_room.json


{
    "code": "Aichi_meeting_room",
    "name": "Aichi_conference room",
    "field1": "id",
    "field2": "floar",
    "field3": "capacities"
}

Aichi_parking.json


{
    "code": "Aichi_parking",
    "name": "Aichi_Parking Lot",
    "field1": "id",
    "field2": "area",
    "field3": "space_number",
    "field4": "user_name",
    "field5": "car_number",
    "field6": "expire"
}

Recommended Posts

Read json file with Python, format it, and output json
[Python3] Read and write with datetime isoformat with json
Read CSV file with Python and convert it to DataFrame as it is
Format json with Vim (with python)
Read json data with python
Read and analyze arff format dataset with python scipy.io
Output log in JSON format with Python standard logging
Divide each PowerPoint slide into a JPG file and output it with python
Output to csv file with Python
JSON encoding and decoding with python
Read CSV file with python (Download & parse CSV file)
Let's read the RINEX file with Python ①
Reading and writing JSON files with Python
Read and write JSON files in Python
[python] Read html file and practice scraping
[Automation] Read mail (msg file) with Python
Read the file with python and delete the line breaks [Notes on reading the file]
How to read a CSV file with Python 2/3
[Python] I introduced Word2Vec and played with it.
[Python] How to read excel file with pandas
Read table data in PDF file with Python
Output python log to both console and file
Create a Photoshop format file (.psd) with python
POST JSON in Python and receive it in PHP
Read line by line from a file with Python
[Python] Use JSON with Python
python input and output
Read Python csv file
[Python] Concatenate a List containing numbers and write it to an output file.
Procedure to load MNIST with python and output to png
Install selenium on Mac and try it with python
Read the csv file and display it in the browser
Parse and visualize JSON (Web application ⑤ with Python + Flask)
How to convert JSON file to CSV file with Python Pandas
Read and write files with Slackbot ~ Bot development with Python ~
Get mail from Gmail and label it with Python3
POST the image with json and receive it with flask
Read the csv file with jupyter notebook and write the graph on top of it
It is easy to execute SQL with Python and output the result in Excel
Programming with Python and Tkinter
Read and write csv file
Encryption and decryption with Python
Read csv with python pandas
Easily format JSON in Python
Python and hardware-Using RS232C with Python-
Python indentation and string format
POST json with Python3 script
Try Python output with Haxe 3.2
Draw netCDF file with python
Read and write a file
Write and read a file
python with pyenv and venv
String format with Python% operator
Download csv file with python
Read Fortran output in python
Works with Python and R
Easily write JSON and Python dataclass conversions with quicktype and dacite
Associate Python Enum with a function and make it Callable
Get the MIME type in Python and determine the file format
Python application: Data handling Part 1: Data formatting and file input / output
Easy with just Python! Output Graphviz figures in draw.io format!