w

示例

本节提供使用各种数据结构和真实世界场景的YAML到JSON转换的综合示例。

基本示例

简单键值对

YAML输入

name: John Doe
age: 30
email: john@example.com
active: true

JSON输出

{
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com",
  "active": true
}

嵌套对象

YAML输入

user:
  personal:
    name: John Doe
    age: 30
  contact:
    email: john@example.com
    phone: '+1-555-0123'
  preferences:
    theme: dark
    notifications: true

JSON输出

{
  "user": {
    "personal": {
      "name": "John Doe",
      "age": 30
    },
    "contact": {
      "email": "john@example.com",
      "phone": "+1-555-0123"
    },
    "preferences": {
      "theme": "dark",
      "notifications": true
    }
  }
}

数组和列表

YAML输入

fruits:
  - apple
  - banana
  - orange
  - grape

numbers:
  - 1
  - 2
  - 3
  - 4
  - 5

JSON输出

{
  "fruits": ["apple", "banana", "orange", "grape"],
  "numbers": [1, 2, 3, 4, 5]
}

复杂示例

混合数据类型

YAML输入

config:
  database:
    host: localhost
    port: 5432
    name: myapp
    ssl: true
    timeout: 30.5
  features:
    - authentication
    - logging
    - monitoring
  users:
    - name: admin
      role: administrator
      permissions:
        - read
        - write
        - delete
    - name: user
      role: standard
      permissions:
        - read

JSON输出

{
  "config": {
    "database": {
      "host": "localhost",
      "port": 5432,
      "name": "myapp",
      "ssl": true,
      "timeout": 30.5
    },
    "features": ["authentication", "logging", "monitoring"],
    "users": [
      {
        "name": "admin",
        "role": "administrator",
        "permissions": ["read", "write", "delete"]
      },
      {
        "name": "user",
        "role": "standard",
        "permissions": ["read"]
      }
    ]
  }
}

多行字符串

YAML输入

description: |
  This is a multi-line
  description that spans
  multiple lines and preserves
  line breaks.

summary: >
  This is a folded string
  that will be converted
  to a single line with
  spaces between words.

JSON输出

{
  "description": "This is a multi-line\ndescription that spans\nmultiple lines and preserves\nline breaks.\n",
  "summary": "This is a folded string that will be converted to a single line with spaces between words.\n"
}

真实世界示例

Docker Compose配置

YAML输入

version: '3.8'
services:
  web:
    image: nginx:alpine
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./html:/usr/share/nginx/html
    environment:
      - NGINX_HOST=localhost
      - NGINX_PORT=80
    depends_on:
      - app

  app:
    image: node:16-alpine
    working_dir: /app
    volumes:
      - .:/app
    command: npm start
    environment:
      - NODE_ENV=production
      - PORT=3000

JSON输出

{
  "version": "3.8",
  "services": {
    "web": {
      "image": "nginx:alpine",
      "ports": ["80:80", "443:443"],
      "volumes": ["./html:/usr/share/nginx/html"],
      "environment": ["NGINX_HOST=localhost", "NGINX_PORT=80"],
      "depends_on": ["app"]
    },
    "app": {
      "image": "node:16-alpine",
      "working_dir": "/app",
      "volumes": [".:/app"],
      "command": "npm start",
      "environment": ["NODE_ENV=production", "PORT=3000"]
    }
  }
}

Kubernetes部署

YAML输入

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.14.2
          ports:
            - containerPort: 80
          resources:
            requests:
              memory: '64Mi'
              cpu: '250m'
            limits:
              memory: '128Mi'
              cpu: '500m'

JSON输出

{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "metadata": {
    "name": "nginx-deployment",
    "labels": {
      "app": "nginx"
    }
  },
  "spec": {
    "replicas": 3,
    "selector": {
      "matchLabels": {
        "app": "nginx"
      }
    },
    "template": {
      "metadata": {
        "labels": {
          "app": "nginx"
        }
      },
      "spec": {
        "containers": [
          {
            "name": "nginx",
            "image": "nginx:1.14.2",
            "ports": [
              {
                "containerPort": 80
              }
            ],
            "resources": {
              "requests": {
                "memory": "64Mi",
                "cpu": "250m"
              },
              "limits": {
                "memory": "128Mi",
                "cpu": "500m"
              }
            }
          }
        ]
      }
    }
  }
}

GitHub Actions工作流

YAML输入

name: CI/CD Pipeline
on:
  push:
    branches: [main, develop]
  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'
          cache: 'npm'
      - name: Install dependencies
        run: npm ci
      - name: Run tests
        run: npm test
      - name: Run linting
        run: npm run lint

  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to production
        run: echo "Deploying to production..."

JSON输出

{
  "name": "CI/CD Pipeline",
  "on": {
    "push": {
      "branches": ["main", "develop"]
    },
    "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",
            "cache": "npm"
          }
        },
        {
          "name": "Install dependencies",
          "run": "npm ci"
        },
        {
          "name": "Run tests",
          "run": "npm test"
        },
        {
          "name": "Run linting",
          "run": "npm run lint"
        }
      ]
    },
    "deploy": {
      "needs": "test",
      "runs-on": "ubuntu-latest",
      "if": "github.ref == 'refs/heads/main'",
      "steps": [
        {
          "uses": "actions/checkout@v3"
        },
        {
          "name": "Deploy to production",
          "run": "echo \"Deploying to production...\""
        }
      ]
    }
  }
}

高级示例

带锚点和别名的YAML

YAML输入

defaults: &defaults
  adapter: postgresql
  host: localhost
  port: 5432

development:
  <<: *defaults
  database: myapp_development

test:
  <<: *defaults
  database: myapp_test

production:
  <<: *defaults
  database: myapp_production
  host: prod-db.example.com

JSON输出

{
  "defaults": {
    "adapter": "postgresql",
    "host": "localhost",
    "port": 5432
  },
  "development": {
    "adapter": "postgresql",
    "host": "localhost",
    "port": 5432,
    "database": "myapp_development"
  },
  "test": {
    "adapter": "postgresql",
    "host": "localhost",
    "port": 5432,
    "database": "myapp_test"
  },
  "production": {
    "adapter": "postgresql",
    "host": "prod-db.example.com",
    "port": 5432,
    "database": "myapp_production"
  }
}

复杂嵌套结构

YAML输入

api:
  version: v1
  endpoints:
    users:
      GET:
        path: /users
        parameters:
          - name: page
            type: integer
            required: false
            default: 1
          - name: limit
            type: integer
            required: false
            default: 10
        responses:
          200:
            description: List of users
            schema:
              type: array
              items:
                type: object
                properties:
                  id:
                    type: integer
                  name:
                    type: string
                  email:
                    type: string
      POST:
        path: /users
        parameters:
          - name: user
            type: object
            required: true
            schema:
              type: object
              required:
                - name
                - email
              properties:
                name:
                  type: string
                email:
                  type: string
        responses:
          201:
            description: User created
          400:
            description: Bad request

JSON输出

{
  "api": {
    "version": "v1",
    "endpoints": {
      "users": {
        "GET": {
          "path": "/users",
          "parameters": [
            {
              "name": "page",
              "type": "integer",
              "required": false,
              "default": 1
            },
            {
              "name": "limit",
              "type": "integer",
              "required": false,
              "default": 10
            }
          ],
          "responses": {
            "200": {
              "description": "List of users",
              "schema": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "integer"
                    },
                    "name": {
                      "type": "string"
                    },
                    "email": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        },
        "POST": {
          "path": "/users",
          "parameters": [
            {
              "name": "user",
              "type": "object",
              "required": true,
              "schema": {
                "type": "object",
                "required": ["name", "email"],
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "email": {
                    "type": "string"
                  }
                }
              }
            }
          ],
          "responses": {
            "201": {
              "description": "User created"
            },
            "400": {
              "description": "Bad request"
            }
          }
        }
      }
    }
  }
}

边缘情况和特殊示例

空值和空值

YAML输入

null_value: null
empty_string: ''
empty_array: []
empty_object: {}
tilde_null: ~

JSON输出

{
  "null_value": null,
  "empty_string": "",
  "empty_array": [],
  "empty_object": {},
  "tilde_null": null
}

特殊字符和转义

YAML输入

special_chars: 'Hello, World! @#$%^&*()'
quoted_string: 'This is a "quoted" string'
escaped_string: "Line 1\nLine 2\tTabbed"
unicode_string: 'Hello 世界 🌍'

JSON输出

{
  "special_chars": "Hello, World! @#$%^&*()",
  "quoted_string": "This is a \"quoted\" string",
  "escaped_string": "Line 1\nLine 2\tTabbed",
  "unicode_string": "Hello 世界 🌍"
}

数字和科学记数法

YAML输入

integer: 42
float: 3.14159
scientific: 1.23e+10
negative: -100
zero: 0

JSON输出

{
  "integer": 42,
  "float": 3.14159,
  "scientific": 12300000000,
  "negative": -100,
  "zero": 0
}

最佳实践示例

结构良好的配置

YAML输入

# 应用程序配置
app:
  name: 'My Application'
  version: '1.0.0'
  environment: production

# 数据库配置
database:
  host: ${DB_HOST:localhost}
  port: ${DB_PORT:5432}
  name: ${DB_NAME:myapp}
  ssl: true

# 功能标志
features:
  authentication: true
  logging: true
  monitoring: false
  analytics: true

# API配置
api:
  base_url: 'https://api.example.com'
  timeout: 30
  retries: 3
  rate_limit: 1000

JSON输出

{
  "app": {
    "name": "My Application",
    "version": "1.0.0",
    "environment": "production"
  },
  "database": {
    "host": "${DB_HOST:localhost}",
    "port": "${DB_PORT:5432}",
    "name": "${DB_NAME:myapp}",
    "ssl": true
  },
  "features": {
    "authentication": true,
    "logging": true,
    "monitoring": false,
    "analytics": true
  },
  "api": {
    "base_url": "https://api.example.com",
    "timeout": 30,
    "retries": 3,
    "rate_limit": 1000
  }
}

常见使用场景

配置文件

  • 应用程序设置:将应用程序配置从YAML转换为JSON
  • 环境变量:转换环境配置
  • 功能标志:转换功能标志配置

API开发

  • OpenAPI规范:将API规范转换为JSON格式
  • 请求/响应模式:转换数据模式
  • API文档:转换文档格式

数据迁移

  • 数据库模式:转换模式定义
  • 数据导出:转换导出的数据格式
  • 系统集成:在系统格式之间转换

测试和开发

  • 测试数据:转换测试配置
  • 模拟数据:转换模拟数据格式
  • 开发工具:转换工具配置

这些示例展示了YAML到JSON转换器工具在各种真实世界场景和用例中的多功能性和强大功能。

这个页面对您有帮助吗?