← ブログに戻る

JSON Beautifier完全ガイド

JSONを美化してフォーマットする方法。オンラインツール、エディタ、プログラミング言語での整形方法。

Big JSON Team10 分で読めますtools
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

10 分読む

# JSON Beautifier完全ガイド

JSONを読みやすく整形するための包括的なガイドです。

JSON Beautifierとは

JSON Beautifier(美化ツール)は、圧縮されたJSONを読みやすい形式に変換するツールです。

Before(圧縮)

{"name":"田中太郎","age":30,"address":{"city":"東京","zip":"100-0001"},"hobbies":["読書","旅行"]}

After(美化)

{

"name": "田中太郎",

"age": 30,

"address": {

"city": "東京",

"zip": "100-0001"

},

"hobbies": [

"読書",

"旅行"

]

}

なぜ美化が必要か

利点

  • 📖 可読性向上 - 構造が明確に
  • 🐛 デバッグ容易 - エラーを見つけやすい
  • 👥 共同作業 - チームでの理解が容易
  • レビュー - コードレビューが簡単
  • 📝 ドキュメント - ドキュメントに最適

オンラインBeautifier

1. BigJSON.online

URL: bigjson.online 特徴:
  • 自動美化
  • リアルタイムプレビュー
  • 大きなファイル対応
  • ダウンロード機能
  • プライバシー保護

使い方:
  • JSONを貼り付け
  • 自動フォーマット
  • コピーまたはダウンロード
  • 2. JSONFormatter.org

    特徴:
    • 美化とミニファイ
    • 検証
    • ツリービュー
    • URLエンコード

    3. JSONLint

    特徴:
    • 検証 + 美化
    • エラー報告
    • シンプルなUI

    4. FreeFormatter

    特徴:
    • 複数フォーマット
    • カスタムインデント
    • ソート機能

    テキストエディタ

    Visual Studio Code

    組み込み機能

    ショートカット:
    • Windows/Linux: Shift + Alt + F
    • macOS: Shift + Option + F

    コマンドパレット:
  • Ctrl/Cmd + Shift + P
  • "Format Document" を入力
  • Enter
  • 設定

    {
    

    "editor.formatOnSave": true,

    "editor.formatOnPaste": true,

    "editor.tabSize": 2,

    "[json]": {

    "editor.defaultFormatter": "esbenp.prettier-vscode",

    "editor.insertSpaces": true

    }

    }

    Prettier拡張

    インストール:
  • 拡張機能を開く
  • "Prettier" を検索
  • インストール
  • 設定ファイル (.prettierrc):
    {
    

    "printWidth": 80,

    "tabWidth": 2,

    "useTabs": false,

    "semi": true,

    "singleQuote": false,

    "trailingComma": "none",

    "bracketSpacing": true

    }

    Sublime Text

    パッケージ:
  • Package Control をインストール
  • "Pretty JSON" をインストール
  • ショートカット:
    • Windows/Linux: Ctrl + Alt + J
    • macOS: Cmd + Ctrl + J

    Atom

    パッケージ:
    apm install pretty-json
    使用: Ctrl/Cmd + Shift + P → "Pretty JSON"

    IntelliJ IDEA / WebStorm

    ショートカット:
    • Windows/Linux: Ctrl + Alt + L
    • macOS: Cmd + Option + L

    Vim

    コマンド:
    :%!jq '.'

    または

    :%!python -m json.tool

    プログラミング言語

    JavaScript/Node.js

    ブラウザ

    const jsonString = '{"name":"田中太郎","age":30}';
    

    const obj = JSON.parse(jsonString);

    // 美化(インデント2)

    const beautified = JSON.stringify(obj, null, 2);

    console.log(beautified);

    カスタムインデント

    // タブを使用
    

    JSON.stringify(obj, null, '\t');

    // 4スペース

    JSON.stringify(obj, null, 4);

    // カスタム文字列

    JSON.stringify(obj, null, ' ');

    ファイルの美化

    const fs = require('fs');
    
    

    // ファイルを読み取り

    const raw = fs.readFileSync('input.json', 'utf8');

    const data = JSON.parse(raw);

    // 美化して保存

    fs.writeFileSync(

    'output.json',

    JSON.stringify(data, null, 2)

    );

    Python

    基本

    import json
    
    

    # JSON文字列を美化

    json_str = '{"name":"田中太郎","age":30}'

    data = json.loads(json_str)

    beautified = json.dumps(data, indent=2, ensure_ascii=False)

    print(beautified)

    ファイル処理

    import json
    
    

    # ファイルを読み取り

    with open('input.json', 'r', encoding='utf-8') as f:

    data = json.load(f)

    # 美化して保存

    with open('output.json', 'w', encoding='utf-8') as f:

    json.dump(data, f, indent=2, ensure_ascii=False)

    キーのソート

    beautified = json.dumps(
    

    data,

    indent=2,

    sort_keys=True,

    ensure_ascii=False

    )

    PHP

    <?php
    

    $json = '{"name":"田中太郎","age":30}';

    $data = json_decode($json);

    // 美化

    $beautified = json_encode(

    $data,

    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE

    );

    echo $beautified;

    ?>

    Ruby

    require 'json'
    
    

    json_str = '{"name":"田中太郎","age":30}'

    data = JSON.parse(json_str)

    # 美化

    beautified = JSON.pretty_generate(data)

    puts beautified

    Java

    import com.google.gson.Gson;
    

    import com.google.gson.GsonBuilder;

    String json = "{\"name\":\"田中太郎\",\"age\":30}";

    Gson gson = new GsonBuilder()

    .setPrettyPrinting()

    .create();

    Object obj = gson.fromJson(json, Object.class);

    String beautified = gson.toJson(obj);

    System.out.println(beautified);

    C#

    using System.Text.Json;
    
    

    string json = "{\"name\":\"田中太郎\",\"age\":30}";

    var options = new JsonSerializerOptions

    {

    WriteIndented = true

    };

    var obj = JsonSerializer.Deserialize<object>(json);

    string beautified = JsonSerializer.Serialize(obj, options);

    Console.WriteLine(beautified);

    コマンドラインツール

    jq

    最も強力なツール:
    # 基本の美化
    

    jq '.' input.json

    # ファイルに保存

    jq '.' input.json > output.json

    # キーをソート

    jq -S '.' input.json

    # コンパクト(ミニファイ)

    jq -c '.' input.json

    # カスタムインデント(4スペース)

    jq --indent 4 '.' input.json

    # カラー出力

    jq -C '.' input.json

    Python (コマンドライン)

    # 美化
    

    python -m json.tool input.json output.json

    # 標準入力から

    echo '{"name":"田中"}' | python -m json.tool

    # キーをソート

    python -m json.tool --sort-keys input.json

    Node.js スクリプト

    # NPMグローバルパッケージ
    

    npm install -g json

    # 美化

    json < input.json

    # カスタムインデント

    json -i 4 < input.json

    ブラウザ拡張機能

    JSON Formatter (Chrome)

    インストール:

    Chrome Web Store → "JSON Formatter"

    特徴:
    • 自動フォーマット
    • 構文ハイライト
    • 折りたたみ可能
    • テーマ選択

    JSONView (Firefox)

    特徴:
    • ネイティブJSON表示
    • ツリー表示
    • 検索機能

    高度な美化オプション

    カスタムフォーマット関数

    function customBeautify(obj, options = {}) {
    

    const {

    indent = 2,

    maxLineLength = 80,

    sortKeys = false,

    trailingComma = false

    } = options;

    let result = JSON.stringify(obj, null, indent);

    if (sortKeys) {

    const sorted = sortObjectKeys(obj);

    result = JSON.stringify(sorted, null, indent);

    }

    return result;

    }

    function sortObjectKeys(obj) {

    if (Array.isArray(obj)) {

    return obj.map(sortObjectKeys);

    }

    if (obj !== null && typeof obj === 'object') {

    return Object.keys(obj)

    .sort()

    .reduce((result, key) => {

    result[key] = sortObjectKeys(obj[key]);

    return result;

    }, {});

    }

    return obj;

    }

    コメント付きJSON(JSON5)

    const JSON5 = require('json5');
    
    

    const json5String = {

    // ユーザー情報

    name: "田中太郎",

    age: 30,

    /

    住所情報

    /

    address: {

    city: "東京"

    }

    };

    const obj = JSON5.parse(json5String);

    const beautified = JSON5.stringify(obj, null, 2);

    バッチ処理

    複数ファイルの美化

    Bash

    # すべての.jsonファイルを美化
    

    for file in .json; do

    jq '.' "$file" > "$file.tmp"

    mv "$file.tmp" "$file"

    done

    PowerShell

    Get-ChildItem .json | ForEach-Object {
    

    $content = Get-Content $_.FullName -Raw | ConvertFrom-Json

    $content | ConvertTo-Json -Depth 100 | Set-Content $_.FullName

    }

    Node.js スクリプト

    const fs = require('fs');
    

    const path = require('path');

    const dir = './json-files';

    fs.readdirSync(dir)

    .filter(file => file.endsWith('.json'))

    .forEach(file => {

    const filePath = path.join(dir, file);

    const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));

    fs.writeFileSync(filePath, JSON.stringify(data, null, 2));

    });

    console.log('すべてのファイルを美化しました');

    自動化

    Git Pre-commit Hook

    #!/bin/bash
    

    # .git/hooks/pre-commit

    for file in $(git diff --cached --name-only | grep '.json$'); do

    if [ -f "$file" ]; then

    jq '.' "$file" > "$file.tmp"

    mv "$file.tmp" "$file"

    git add "$file"

    fi

    done

    VS Code タスク

    {
    

    "version": "2.0.0",

    "tasks": [

    {

    "label": "Beautify JSON",

    "type": "shell",

    "command": "jq '.' ${file} > ${file}.tmp && mv ${file}.tmp ${file}",

    "presentation": {

    "reveal": "never"

    }

    }

    ]

    }

    NPM スクリプト

    {
    

    "scripts": {

    "format:json": "prettier --write '*/.json'",

    "beautify": "find . -name '*.json' -exec jq '.' {} \; > /dev/null"

    }

    }

    ベストプラクティス

    1. 一貫したインデント

    推奨:2スペース
    {
    

    "user": {

    "name": "田中太郎"

    }

    }

    2. 適切な改行

    配列の要素が多い場合:
    {
    

    "colors": [

    "赤",

    "青",

    "緑"

    ]

    }

    3. キーのソート(オプション)

    {
    

    "age": 30,

    "city": "東京",

    "name": "田中太郎"

    }

    4. UTF-8エンコーディング

    常にUTF-8を使用:

    // ensure_ascii=false (Python)
    

    json.dumps(data, ensure_ascii=False)

    // Node.js

    fs.writeFileSync('file.json', data, 'utf8');

    トラブルシューティング

    問題1: 無効なJSON

    エラー:
    SyntaxError: Unexpected token
    解決:
  • JSONLintで検証
  • エラー箇所を修正
  • 再度美化
  • 問題2: 文字化け

    原因: エンコーディングの問題 解決:
    # UTF-8で保存
    

    json.dumps(data, ensure_ascii=False)

    問題3: 大きすぎるファイル

    解決:
    • jqを使用(効率的)
    • ストリーミング処理
    • 部分的に美化

    ツール比較

    | ツール | 速度 | 機能 | 使いやすさ |

    |--------|------|------|-----------|

    | BigJSON.online | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |

    | VS Code | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |

    | jq | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |

    | Python | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |

    | オンライン | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |

    まとめ

    クイック選択

    • ブラウザで → BigJSON.online
    • エディタで → VS Code (Shift+Alt+F)
    • コマンドライン → jq
    • プログラム内 → JSON.stringify(obj, null, 2)
    • バッチ処理 → スクリプト

    基本コマンド

    # jq
    

    jq '.' input.json > output.json

    # Python

    python -m json.tool input.json output.json

    # Node.js

    node -e "console.log(JSON.stringify(require('./input.json'), null, 2))"

    JSON Beautifierで、コードの可読性を向上させましょう!

    Share:

    関連記事

    Read in English