0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JSONからHTMLに変換するツールを作ってみた

Last updated at Posted at 2023-12-15

はじめに

HTMLでのデータ表現は分かりやすいですが時に冗長であり、特に複雑なデータ構造を表現する際には保守性が低くなりがちです。
そこで、JSONのシンプルで見やすいデータ形式を利用して、HTMLの生成を行いたいと考えてこのツールを作りました。

プログラムの概要

以下は、Pythonを使用してJSONファイルをHTMLに変換するコマンドラインツールです。このツールでは、argparseを使ってコマンドライン引数を処理し、JSONデータを再帰的にHTMLに変換します。

import os
import json
import argparse as ap
import webbrowser as wb

# コマンドライン引数の設定
parser = ap.ArgumentParser(description='jsonデータからHTMLを作成するツール')
parser.add_argument('input_file', help='入力するjsonファイル')
parser.add_argument('-o', '--open', action='store_true', help='作成したHTMLをブラウザで開きます')
args = parser.parse_args()

def dict_html(struct: dict, indent: int) -> str:
    '''
    辞書データをHTMLテキストに変換します。    
    '''

    html_text = ""
    for (tag, value) in struct.items():    
        html_text += '\t'*indent + f"<{tag}>\n"
        if isinstance(value, dict):
            # 再帰的に呼び出す
            html_text += dict_html(value, indent+1)
        else:
            html_text += '\t'*indent + f"\t{value}\n"
        html_text += '\t'*indent + f"</{tag.split(' ')[0]}>\n"
    return html_text


def change_extension(file_path: str, new_extension: str):
    '''
    ファイルの拡張子を変更します
    '''
    base_path, _ = os.path.splitext(file_path)
    new_file_path = base_path + new_extension    
    return new_file_path

def main():
    path: str = args.input_file

    # ファイルの存在確認
    if not os.path.exists(path):
        print("指定されたファイルは存在しません。")
        return
    
    # ファイルがJSON形式かどうか確認
    try:
        with open(path, mode="r", encoding="utf-8") as file:
            struct: dict = json.load(file)
    except json.JSONDecodeError as e:
        print("JSON形式のファイルではありません。")
        return
    
    html = dict_html(struct, 0)

    new_path = change_extension(path, ".html")
    with open(new_path, mode="w", encoding="utf-8") as html_file:
        html_file.write(html)

    is_open = args.open
    if is_open:
        wb.open(new_path)


if __name__ == "__main__":
    main()

実行

WebページをJSON(19行)ファイルで保存します

{
    "html": {
        "head": {
            "title": "Json-Html"
        },
        "body": {
            "h1": "Json-Html",
            "div": {
                "p": "JSONからHTMLに変換するツールを作ってみた",
                "a href=https://www.github.com/KajizukaTaichi/Json-Html": {
                    "button": "Githubリポジトリ"
                }
            },
            "footer": {
                "p": "&copy; 2023 梶塚太智"
            }
        }
    }
}

環境に拠りますが、このJSONファイルを以下のコマンドでHTML変換します

> python main.py index.json

するとHTMLファイルが作成されます。以下が変換後のHTML(27行)です。

<html>
	<head>
		<title>
			Json-Html
		</title>
	</head>
	<body>
		<h1>
			Json-Html
		</h1>
		<div>
			<p>
				JSONからHTMLに変換するツールを作ってみた
			</p>
			<a href="https://www.github.com/KajizukaTaichi/Json-Html">
				<button>
					Githubリポジトリ
				</button>
			</a>
		</div>
		<footer>
			<p>
				&copy; 2023 梶塚太智
			</p>
		</footer>
	</body>
</html>

まとめ

JSON形式のデータをHTMLに変換することで、よりシンプルで可読性の高いデータ表現が可能です。このツールを作成することで、冗長なHTMLコーディングの手間を省けます。

改善点などのアイデアがあれば、是非Githubにてコントリビューションして頂けると幸いです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?