他のツール
JSON→YAML変換
JSON と YAML 形式の相互変換ツール
ツール概要:JSON ⇄ YAML 変換ツール
JSON(JavaScript Object Notation)とYAML(YAML Ain't Markup Language)は、どちらもデータ交換や設定ファイルで広く使用される形式です。このツールは、JSONとYAMLの相互変換を簡単に行うことができます。
JSON ⇄ YAML 変換ツールとは?
JSON ⇄ YAML 変換ツールはJSONとYAMLの変換を素早く行い、すぐ使える結果を出力します。
使い方
- JSONの内容を貼り付けるかパラメータを入力します。
- YAMLの出力形式を選び、オプションを調整します。
- 結果を確認してコピーまたはダウンロードします。
よくある利用シーン
- JSON↔YAMLのフォーマット移行
- JSONデータをYAMLのワークフローやコード生成に利用
- 変換結果の仕様チェック
❓ よくある質問
Q1: 変換に失敗する/空になる?
A: JSONの入力が正しいか確認してください。
Q2: 出力が違って見える?
A: YAMLのルールに合わせて整形される場合があります。
Q3: 一括処理は?
A: 安定のため小分けにして処理してください。
✨ 主な機能
- 🔄 双方向変換:JSONからYAML、YAMLからJSONの両方向変換をサポート
- ✅ 形式検証:入力データの構文チェックとエラー表示
- 🎨 美しい出力:読みやすい形式でフォーマット
- 📋 ワンクリックコピー:変換結果を直接コピー可能
- 🌐 多言語対応:日本語などのUnicode文字に完全対応
📖 使用例
JSON → YAML 変換
入力JSON:
{
"name": "ツールミ",
"version": "1.0.0",
"description": "便利なオンラインツール集",
"features": [
"JSON変換",
"YAML変換",
"データ検証"
],
"config": {
"debug": true,
"port": 3000,
"database": {
"host": "localhost",
"port": 5432
}
}
}
変換後YAML:
name: ツールミ
version: 1.0.0
description: 便利なオンラインツール集
features:
- JSON変換
- YAML変換
- データ検証
config:
debug: true
port: 3000
database:
host: localhost
port: 5432
YAML → JSON 変換
入力YAML:
# アプリケーション設定
app:
name: サンプルアプリ
version: 2.1.0
server:
host: 0.0.0.0
port: 8080
ssl:
enabled: true
cert_path: /etc/ssl/cert.pem
database:
type: postgresql
host: localhost
port: 5432
credentials:
username: admin
password: secret
変換後JSON:
{
"app": {
"name": "サンプルアプリ",
"version": "2.1.0"
},
"server": {
"host": "0.0.0.0",
"port": 8080,
"ssl": {
"enabled": true,
"cert_path": "/etc/ssl/cert.pem"
}
},
"database": {
"type": "postgresql",
"host": "localhost",
"port": 5432,
"credentials": {
"username": "admin",
"password": "secret"
}
}
}
🎯 応用シーン
1. 設定ファイル管理
アプリケーション設定の形式変換:
// 設定ファイル変換ユーティリティ
class ConfigConverter {
constructor() {
this.yamlParser = require('js-yaml');
}
// JSON設定をYAMLに変換
jsonToYaml(jsonConfig) {
try {
const configObject = typeof jsonConfig === 'string'
? JSON.parse(jsonConfig)
: jsonConfig;
return this.yamlParser.dump(configObject, {
indent: 2,
lineWidth: 120,
noRefs: true
});
} catch (error) {
throw new Error(`JSON→YAML変換エラー: ${error.message}`);
}
}
// YAML設定をJSONに変換
yamlToJson(yamlConfig, pretty = true) {
try {
const configObject = this.yamlParser.load(yamlConfig);
return pretty
? JSON.stringify(configObject, null, 2)
: JSON.stringify(configObject);
} catch (error) {
throw new Error(`YAML→JSON変換エラー: ${error.message}`);
}
}
// 設定ファイルの検証
validateConfig(config, format) {
try {
if (format === 'json') {
JSON.parse(config);
return { valid: true, message: 'JSON形式が正しいです' };
} else if (format === 'yaml') {
this.yamlParser.load(config);
return { valid: true, message: 'YAML形式が正しいです' };
}
} catch (error) {
return {
valid: false,
message: `${format.toUpperCase()}形式エラー: ${error.message}`
};
}
}
// 設定ファイルの移行
migrateConfig(oldConfig, oldFormat, newFormat) {
try {
// 元の形式を検証
const validation = this.validateConfig(oldConfig, oldFormat);
if (!validation.valid) {
throw new Error(validation.message);
}
// 変換実行
if (oldFormat === 'json' && newFormat === 'yaml') {
return this.jsonToYaml(oldConfig);
} else if (oldFormat === 'yaml' && newFormat === 'json') {
return this.yamlToJson(oldConfig);
} else {
throw new Error('サポートされていない変換形式です');
}
} catch (error) {
throw new Error(`設定移行エラー: ${error.message}`);
}
}
}
// 使用例
const converter = new ConfigConverter();
// 既存のJSON設定をYAMLに移行
const jsonConfig = `{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp"
},
"redis": {
"host": "localhost",
"port": 6379
}
}`;
try {
const yamlConfig = converter.migrateConfig(jsonConfig, 'json', 'yaml');
console.log('YAML設定ファイル:');
console.log(yamlConfig);
} catch (error) {
console.error('変換エラー:', error.message);
}
2. API ドキュメント変換
OpenAPI仕様書の形式変換:
// OpenAPI仕様書変換ツール
class OpenAPIConverter {
constructor() {
this.yaml = require('js-yaml');
}
// JSON形式のOpenAPI仕様をYAMLに変換
convertToYaml(openApiJson) {
try {
const spec = typeof openApiJson === 'string'
? JSON.parse(openApiJson)
: openApiJson;
// OpenAPI仕様の基本検証
if (!spec.openapi && !spec.swagger) {
throw new Error('有効なOpenAPI仕様ではありません');
}
return this.yaml.dump(spec, {
indent: 2,
lineWidth: 120,
noRefs: true,
sortKeys: false
});
} catch (error) {
throw new Error(`OpenAPI変換エラー: ${error.message}`);
}
}
// YAML形式のOpenAPI仕様をJSONに変換
convertToJson(openApiYaml, minify = false) {
try {
const spec = this.yaml.load(openApiYaml);
// OpenAPI仕様の基本検証
if (!spec.openapi && !spec.swagger) {
throw new Error('有効なOpenAPI仕様ではありません');
}
return minify
? JSON.stringify(spec)
: JSON.stringify(spec, null, 2);
} catch (error) {
throw new Error(`OpenAPI変換エラー: ${error.message}`);
}
}
// 仕様書の情報を抽出
extractApiInfo(spec) {
try {
const apiSpec = typeof spec === 'string'
? this.yaml.load(spec)
: spec;
return {
version: apiSpec.openapi || apiSpec.swagger,
title: apiSpec.info?.title || 'タイトル未設定',
description: apiSpec.info?.description || '説明なし',
version: apiSpec.info?.version || '1.0.0',
servers: apiSpec.servers || [],
pathCount: Object.keys(apiSpec.paths || {}).length,
componentCount: Object.keys(apiSpec.components?.schemas || {}).length
};
} catch (error) {
throw new Error(`仕様書解析エラー: ${error.message}`);
}
}
}
// 使用例
const apiConverter = new OpenAPIConverter();
// サンプルOpenAPI仕様(JSON)
const openApiJson = {
"openapi": "3.0.0",
"info": {
"title": "ツールミ API",
"description": "便利なツールのAPI仕様",
"version": "1.0.0"
},
"servers": [
{
"url": "https://api.toolmi.com/v1",
"description": "本番環境"
}
],
"paths": {
"/tools": {
"get": {
"summary": "ツール一覧取得",
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Tool"
}
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Tool": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"description": {
"type": "string"
}
}
}
}
}
};
// JSON → YAML変換
try {
const yamlSpec = apiConverter.convertToYaml(openApiJson);
console.log('YAML形式のOpenAPI仕様:');
console.log(yamlSpec);
// 仕様書情報の抽出
const apiInfo = apiConverter.extractApiInfo(openApiJson);
console.log('API情報:', apiInfo);
} catch (error) {
console.error('変換エラー:', error.message);
}
3. CI/CD パイプライン設定
GitHub ActionsやDockerの設定変換:
// CI/CD設定変換ツール
class CICDConfigConverter {
constructor() {
this.yaml = require('js-yaml');
}
// GitHub Actions設定の変換
convertGitHubActions(config, targetFormat) {
try {
if (targetFormat === 'yaml') {
const workflow = typeof config === 'string' ? JSON.parse(config) : config;
return this.yaml.dump(workflow, { indent: 2 });
} else {
const workflow = this.yaml.load(config);
return JSON.stringify(workflow, null, 2);
}
} catch (error) {
throw new Error(`GitHub Actions設定変換エラー: ${error.message}`);
}
}
// Docker Compose設定の変換
convertDockerCompose(config, targetFormat) {
try {
if (targetFormat === 'yaml') {
const compose = typeof config === 'string' ? JSON.parse(config) : config;
return this.yaml.dump(compose, { indent: 2 });
} else {
const compose = this.yaml.load(config);
return JSON.stringify(compose, null, 2);
}
} catch (error) {
throw new Error(`Docker Compose設定変換エラー: ${error.message}`);
}
}
// 設定ファイルの検証
validateCIConfig(config, type) {
try {
const configObj = typeof config === 'string' ? this.yaml.load(config) : config;
switch (type) {
case 'github-actions':
if (!configObj.on || !configObj.jobs) {
throw new Error('GitHub Actions設定に必要なフィールドがありません');
}
break;
case 'docker-compose':
if (!configObj.version || !configObj.services) {
throw new Error('Docker Compose設定に必要なフィールドがありません');
}
break;
default:
throw new Error('サポートされていない設定タイプです');
}
return { valid: true, message: '設定が正しいです' };
} catch (error) {
return { valid: false, message: error.message };
}
}
}
// 使用例
const cicdConverter = new CICDConfigConverter();
// GitHub Actions設定例(YAML)
const githubActionsYaml = `
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
`;
try {
// YAML → JSON変換
const jsonConfig = cicdConverter.convertGitHubActions(githubActionsYaml, 'json');
console.log('JSON形式のGitHub Actions設定:');
console.log(jsonConfig);
// 設定の検証
const validation = cicdConverter.validateCIConfig(githubActionsYaml, 'github-actions');
console.log('検証結果:', validation);
} catch (error) {
console.error('変換エラー:', error.message);
}
🔧 技術詳細
JSON と YAML の特徴比較
| 特徴 | JSON | YAML |
|---|---|---|
| 可読性 | 中程度 | 高い |
| ファイルサイズ | 小さい | 大きい |
| コメント | 不可 | 可能 |
| 複数行文字列 | 不可 | 可能 |
| データ型 | 限定的 | 豊富 |
| パース速度 | 高速 | 中程度 |
変換時の注意点
// 変換時の注意点とベストプラクティス
const conversionBestPractices = {
// コメントの処理
comments: {
issue: 'JSONはコメントをサポートしないため、YAML→JSON変換時にコメントが失われる',
solution: '重要な情報はコメントではなくdescriptionフィールドに記載'
},
// データ型の違い
dataTypes: {
issue: 'YAMLは日付、null、ブール値などをより柔軟に表現',
solution: '変換後にデータ型を確認し、必要に応じて調整'
},
// 複数行文字列
multilineStrings: {
issue: 'YAMLの複数行文字列(|, >)はJSONでは単一文字列になる',
solution: '改行文字(\\n)を使用して表現'
},
// 参照とアンカー
references: {
issue: 'YAMLのアンカー(&)と参照(*)はJSONでは展開される',
solution: '重複データが発生する可能性があることを認識'
}
};
💡 使用のコツ
- 形式選択:設定ファイルにはYAML、API通信にはJSONが適している
- 検証重要:変換前後で必ずデータの整合性を確認
- コメント活用:YAMLではコメントを活用して可読性を向上
- バックアップ:重要な設定ファイルは変換前にバックアップを作成
⚠️ 注意事項
- コメント消失:YAML→JSON変換時にコメントが失われる
- データ型変化:変換時にデータ型が変わる可能性がある
- 構文エラー:無効な形式の入力はエラーになる
- 文字エンコーディング:UTF-8エンコーディングを使用することを推奨
🚀 使い方
- データ入力:変換したいJSONまたはYAMLデータを入力ボックスに貼り付け
- 変換方向選択:「JSON→YAML」または「YAML→JSON」を選択
- 変換実行:「変換」ボタンをクリックして変換を実行
- 結果確認:変換結果が出力エリアに表示される
- コピー使用:「コピー」ボタンで結果をクリップボードにコピー
ヒント:このツールはクライアント側でローカル処理を行い、データをサーバーに送信しないため、機密情報も安全に変換できます。