Toonade

Exemples de code et intégrations

Exemples de code et snippets d'intégration prêts à l'emploi pour le format TOON. Copiez-collez des exemples pour vos langages et frameworks préférés.

Installation

Installez le SDK de format Toon en utilisant npm

Installer le package

npm install @toon-format/toon

Utilisation de base

Convertissez JSON en Toon et vice versa

Encoder JSON en Toon

import { encode, decode } from '@toon-format/toon';

// Convert JSON to Toon
const json = {
  items: [
    { sku: "A1", qty: 2, price: 9.99 },
    { sku: "B2", qty: 1, price: 14.5 }
  ]
};

const toon = encode(json);
console.log(toon);
// Output:
// items[2]{sku,qty,price}:
//   A1,2,9.99
//   B2,1,14.5

Décoder Toon en JSON

import { decode } from '@toon-format/toon';

const toonString = `items[2]{sku,qty,price}:
  A1,2,9.99
  B2,1,14.5`;

const json = decode(toonString);
console.log(json);
// Output: { items: [{ sku: "A1", qty: 2, price: 9.99 }, ...] }

Gestion des erreurs

Gérez les erreurs avec élégance

Exemple try-catch

import { encode, decode } from '@toon-format/toon';

try {
  const json = { name: "Toonade", version: "1.0.0" };
  const toon = encode(json);
  console.log(toon);
} catch (error) {
  console.error('Encoding failed:', error);
}

try {
  const invalidToon = "invalid toon format";
  const json = decode(invalidToon);
} catch (error) {
  console.error('Decoding failed:', error);
}

Types TypeScript

Utilisez avec TypeScript pour la sécurité des types

Définitions de types

import { encode, decode } from '@toon-format/toon';

interface Product {
  sku: string;
  qty: number;
  price: number;
}

interface Inventory {
  items: Product[];
}

const inventory: Inventory = {
  items: [
    { sku: "A1", qty: 2, price: 9.99 }
  ]
};

const toon = encode(inventory);
const decoded: Inventory = decode(toon) as Inventory;