w

API Reference

This document provides technical details about the JSON to YAML Converter tool's implementation and API.

Technical Overview

Core Technology

  • Frontend: Vue.js 3 with Composition API
  • YAML Processing: js-yaml library
  • State Management: Pinia store
  • Styling: TailwindCSS

Browser Requirements

  • Modern Browsers: Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
  • JavaScript: ES6+ support required
  • Local Storage: Required for history functionality

Conversion Process

JSON Parsing

// JSON validation and parsing
const jsonObj = JSON.parse(jsonInput.value);

YAML Generation

// YAML conversion with options
const yamlOutput = yaml.dump(jsonObj, {
  indent: 2, // 2-space indentation
  lineWidth: -1, // No line wrapping
  noRefs: true, // Prevent reference duplication
  sortKeys: false, // Maintain original key order
});

Error Handling

try {
  const jsonObj = JSON.parse(jsonInput.value);
  yamlOutput.value = yaml.dump(jsonObj, options);
} catch (error) {
  hasError.value = true;
  errorMessage.value = error.message;
}

State Management

Pinia Store Structure

interface ToolsState {
  jsonToYaml: {
    history: Array<{
      id: string;
      input: string;
      output: string;
      inputLength: number;
      outputLength: number;
      inputPreview: string;
      timestamp: number;
    }>;
  };
}

History Management

// Add to history
addJsonToYamlHistory(record: {
  id: string;
  input: string;
  output: string;
  inputLength: number;
  outputLength: number;
  inputPreview: string;
  timestamp: number;
});

// Remove from history
removeJsonToYamlHistory(id: string);

// Clear all history
clearJsonToYamlHistory();

Component API

Main Component

<template>
  <ToolLayout id="json-to-yaml" doc-href="/docs/core/json-to-yaml/introduction">
    <!-- Tool content -->
  </ToolLayout>
</template>

Props and Events

  • id: Tool identifier for routing and state management
  • doc-href: Documentation link for the tool
  • class: Additional CSS classes

Utility Functions

Copy to Clipboard

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
  } catch (error) {
    console.error('复制失败:', error);
  }
};

File Download

const downloadYaml = () => {
  if (!yamlOutput.value.trim() || hasError.value) return;

  const blob = new Blob([yamlOutput.value], { type: 'text/yaml' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'output.yaml';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

Date Formatting

const formatDate = (timestamp: number) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(timestamp));
};

Configuration Options

YAML Generation Options

const yamlOptions = {
  indent: 2, // Indentation level
  lineWidth: -1, // Line width (-1 for no wrapping)
  noRefs: true, // Prevent reference duplication
  sortKeys: false, // Maintain original key order
  quotingType: '"', // Quote style
  forceQuotes: false, // Force quotes on all strings
};

Formatting Options

// Pretty print
const formatYaml = () => {
  const yamlObj = yaml.load(yamlOutput.value);
  yamlOutput.value = yaml.dump(yamlObj, {
    indent: 2,
    lineWidth: -1,
    noRefs: true,
    sortKeys: false,
  });
};

// Minify
const minifyYaml = () => {
  const yamlObj = yaml.load(yamlOutput.value);
  yamlOutput.value = yaml.dump(yamlObj, {
    indent: 0,
    lineWidth: -1,
    noRefs: true,
    sortKeys: false,
  });
};

Error Handling

JSON Validation

const validateJson = (jsonString: string): boolean => {
  try {
    JSON.parse(jsonString);
    return true;
  } catch (error) {
    return false;
  }
};

Error Types

  • SyntaxError: Invalid JSON syntax
  • TypeError: Data type issues
  • ReferenceError: Undefined variables
  • Custom Errors: Application-specific errors

Performance Considerations

Memory Management

  • Efficient Processing: Optimized for large JSON files
  • Automatic Cleanup: Memory cleared on page unload
  • History Limits: Maximum 50 history entries

Browser Compatibility

  • Feature Detection: Checks for required browser features
  • Graceful Degradation: Fallbacks for older browsers
  • Performance Monitoring: Tracks conversion performance

Integration Examples

Embedding in Applications

// Initialize the converter
const converter = new JsonToYamlConverter({
  options: {
    indent: 2,
    lineWidth: -1,
    noRefs: true,
    sortKeys: false,
  },
});

// Convert JSON to YAML
const yamlResult = converter.convert(jsonData);

Custom Configuration

// Custom YAML options
const customOptions = {
  indent: 4, // 4-space indentation
  lineWidth: 80, // 80-character line width
  noRefs: false, // Allow references
  sortKeys: true, // Sort keys alphabetically
  quotingType: "'", // Single quotes
  forceQuotes: true, // Force quotes on all strings
};

Testing

Unit Tests

describe('JSON to YAML Converter', () => {
  test('converts simple JSON to YAML', () => {
    const json = '{"name": "John", "age": 30}';
    const expected = 'name: John\nage: 30\n';
    expect(convertJsonToYaml(json)).toBe(expected);
  });

  test('handles nested objects', () => {
    const json = '{"user": {"name": "John", "age": 30}}';
    const expected = 'user:\n  name: John\n  age: 30\n';
    expect(convertJsonToYaml(json)).toBe(expected);
  });
});

Integration Tests

describe('Tool Integration', () => {
  test('history management', () => {
    const store = useToolsStore();
    store.addJsonToYamlHistory(mockRecord);
    expect(store.jsonToYaml.history).toContain(mockRecord);
  });
});

Browser Support

Required Features

  • ES6 Modules: For modern JavaScript
  • Local Storage: For history functionality
  • Clipboard API: For copy functionality
  • Blob API: For file downloads

Polyfills

  • No Polyfills Required: Uses only modern browser features
  • Graceful Degradation: Falls back gracefully on older browsers
  • Feature Detection: Checks for required features

Security Considerations

Client-Side Processing

  • No Server Communication: All processing happens locally
  • No Data Transmission: Data never leaves the browser
  • Local Storage Only: History stored locally only

Input Validation

  • JSON Validation: Validates JSON before processing
  • Error Handling: Comprehensive error handling
  • Sanitization: Output is properly formatted

Troubleshooting

Common Issues

  1. Invalid JSON: Check JSON syntax
  2. Large Files: Break into smaller chunks
  3. Browser Compatibility: Use modern browser
  4. Memory Issues: Clear history regularly

Debug Information

  • Console Logging: Detailed error messages
  • Error Tracking: Comprehensive error handling
  • Performance Metrics: Conversion timing information

Future Enhancements

Planned Features

  • Batch Processing: Multiple file conversion
  • Custom Schemas: Schema validation
  • Advanced Formatting: More formatting options
  • Export Formats: Additional export formats

API Improvements

  • REST API: Server-side processing option
  • WebSocket: Real-time collaboration
  • Plugin System: Extensible architecture
Was this page helpful?