svgson

repository·master·Indexed 19 days ago

https://github.com/elrumordelaluz/svgson

A tool to transform SVG files and strings into JSON objects (AST) and back into SVG strings. It provides asynchronous (parse) and synchronous (parseSync) parsing methods, as well as a stringify function to convert ASTs back to SVG. It is designed for manipulating SVG data with JavaScript or storing SVG structures in NoSQL databases.

Tokens
1.4K
Snippets
4
Records
7
Agent score
17%

What's inside svgson

  1. Convert SVG to JSON AST and back

    master

    Use parse to convert an SVG string into a JSON Abstract Syntax Tree (AST) and stringify to convert that AST back into an SVG string.

    const { parse, stringify } = require('svgson')
    
    // Convert SVG string to JSON AST
    parse(`<svg><line x1="70" y1="80" x2="250" y2="150" /></svg>`).then((json) => {
      console.log(json)
    
      // Convert JSON AST back to SVG string
      const mysvg = stringify(json)
      console.log(mysvg)
    })
    const { parse, stringify } = require('svgson')
    
    // ----------------------------
    // Convert SVG to JSON AST
    // ----------------------------
    parse(`
      <svg>
        <line
          stroke= "#bada55"
          stroke-width= "2"
          stroke-linecap= "round"
          x1= "70"
          y1= "80"
          x2= "250"
          y2= "150">
        </line>
      </svg>`).then((json) => {
      console.log(JSON.stringify(json, null, 2))
      /*
        { ... }
      */
    
      // ---------------------------------
      // Convert JSON AST back to SVG
      // ---------------------------------
      const mysvg = stringify(json)
      /* returns the SVG as string */
    })
  2. Use svgson.stringify

    master

    svgson.stringify(ast[, options]) converts a svgson parsed AST back into an SVG string.

    Parameters

    • ast (Object | Array): The parsed svgson result.
    • options (Object):
      • transformAttr (Function): A function applied to each attribute during stringification. It receives (key, value, escape) and must return the key/attribute string. Defaults to function(key, value, escape) { return ${key}="${escape(value)} };.
      • transformNode (Function): A function applied to each node during stringification. Useful for reshaping nodes or updating values. Returns the node. Defaults to function(node){ return node }.
      • selfClose (Boolean): Whether to use self-closing tags. Defaults to true.

    Pretty Printing

    To generate formatted SVG output, combine stringify with the pretty npm module:

    const pretty = require('pretty')
    const formatted = pretty(svg)
  3. Use svgson.parse

    master

    svgson.parse(input[, options]) is an asynchronous function that returns a Promise resolving to the JSON AST of the provided SVG string.

    Parameters

    • input (String): The SVG string to parse.
    • options (Object):
      • transformNode (Function): A function applied to each node during parsing. Useful for reshaping nodes or setting default attributes. Returns the node. Defaults to function(node){ return node }.
      • camelcase (Boolean): If true, applies camelCase to attributes. Defaults to false.
  4. Parse SVG to JSON using svgsonSync

    master

    Use svgsonSync to synchronously convert an SVG string or file path into a JSON object. You can provide an options object to transform the resulting nodes or to enable camelCase for attribute names.

    Options:

    • transformNode: A function (node) => node that receives the parsed node and allows you to modify it before returning. Defaults to an identity function.
    • camelcase: A boolean that, when set to true, applies camelCase to the attribute names in the resulting object. Defaults to false.
    import { svgsonSync } from 'svgson';
    
    const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100"></svg>';
    
    // Basic usage
    const json = svgsonSync(svg);
    
    // Usage with camelCase and custom transformation
    const jsonWithCamel = svgsonSync(svg, {
      camelcase: true,
      transformNode: (node) => {
        node.customProperty = 'value';
        return node;
      }
    });
  5. Parse SVG to JSON asynchronously using svgson

    master

    The default export svgson provides an asynchronous version of the parser that returns a Promise. It accepts the same arguments as svgsonSync and resolves with the parsed JSON object or rejects if an error occurs during parsing.

    import svgson from 'svgson';
    
    const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100"></svg>';
    
    async function run() {
      try {
        const json = await svgson(svg, { camelcase: true });
        console.log(json);
      } catch (err) {
        console.error(err);
      }
    }
    
    run();