Giter VIP home page Giter VIP logo

svgson's Introduction

svgson

Simple tool to transform svg files and Strings into Object or JSON.

Useful to manipulate SVG with js, to store in noSQL databses.


Travis Codecov Version Download MIT License

v2 docs

Install

yarn add svgson

Usage

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))
  /*
    {
      name: 'svg',
      type: 'element',
      value: '',
      attributes: {},
      parent: null,
      children: [
        {
          name: 'line',
          type: 'element',
          value: '',
          attributes: {
            stroke: '#bada55',
            'stroke-width': '2',
            'stroke-linecap': 'round',
            x1: '70',
            y1: '80',
            x2: '250',
            y2: '150'
          },
          parent: null,
          children: []
        }
      ]
    }
  */

  // -------------------------------
  // Convert JSON AST back to SVG
  // -------------------------------
  const mysvg = stringify(json)
  /* returns the SVG as string */
})

umd usage

const svgson = require('svgson')
svgson
  .parse(
    `<svg>
      <line
        stroke= "#bada55"
        stroke-width= "2"
        stroke-linecap= "round"
        x1= "70"
        y1= "80"
        x2= "250"
        y2= "150">
      </line>
    </svg>`
  )
  .then(function(json) {
    console.log(JSON.stringify(json, null, 2)
  )
 
mysvg = svgson.stringify(json)
  

Test in browser here

API

svgson.parse

svgson.parse(input[, options])

Returns: Promise

  • input

    Type: String

  • options.transformNode

    Function to apply on each node when parsing, useful when need to reshape nodes or set default attributes.

    Type: Function that returns the node

    Default:

    function(node){
      return node
    }
  • options.camelcase

    Apply camelCase into attributes

    Type: Boolean

    Default: false

svgson.parseSync

Added in 3.1.0

svgson.parseSync(input[, options])

This function is a synchronous version of svgson.parse. The arguments are the same, but unlike svgson.parse, the return value is not wrapped in a Promise.

Returns: Object [Object]

svgson.stringify

svg = svgson.stringify(ast[, options])

Returns: String

  • ast

    svgson parsed result.

    Type: Object [Object]

  • options.transformAttr

    Function to apply on each attribute when stringifying.

    Type: Function that returns the key/attribute string with the ability to use the escape function on it.

    Default:

    function(key, value, escape) {
      return `${key}="${escape(value)}"`
    }
  • options.transformNode

Function to apply on each node when stringifying, useful when need to reshape nodes or change/update values.

Type: Function that returns the node

Default:

function(node){
  return node
}
  • options.selfClose

    Type: Boolean

    Default: true

  • Pretty Printing

    In order to generate pretty formatted SVG output, use pretty npm module:

    pretty = require('pretty')
    formatted = pretty(svg)

Related

svgson-cli Transform SVG into Object from the Command Line

element-to-path Convert SVG element into path

path-that-svg Convert entire SVG with path

svg-path-tools Tools to manipulate SVG path (d)

License

MIT © Lionel T

svgson's People

Contributors

dabbott avatar dependabot[bot] avatar elrumordelaluz avatar gu5taf avatar j1mie avatar mnbuyskih avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

svgson's Issues

Can i use this tool to convert my SVG elements to JSON?

Hi Lionel,

Sorry if this is not a right place to ask questions.
I'm building a web app which allows users to create SVG based charts with D3.js and then save them.(These charts will then upload to a server) The problem here is that I cannot convert SVGs to JSONs and send them to the server. I have googled for a few hours and come across your project. It looks like a good fit for my app. But I'm not quite sure if it's capable of:

  1. Can be imported with ES6 module syntax or commonJS? I have read through your docs but still not quite understand the browser part.
  2. It seems like it only converts SVGs to JSON but not the reverse?

Thank you! Hope you're doing well!

Consider using ^ or ~ versions in package.json

By making the dependency versions more flexible for downstream users you could decrease the possibility that your package becomes a bottleneck for an npm audit fix. I thought of this because I noticed the version we were using of svgson depended on a fixed version of svgo which had a vulnerability. Turns out the only way I can fix it is to do a major upgrade of svgson anyway (it was pre-1.0 svgo), but I noticed you're making lots of commits in the repo just to upgrade dependencies by a patch version increment. You might need to do this less often if you allow flexibility. Downstream users will have their own lockfiles anyway.

Cheers - thanks for sharing the project!

Is repo still active?

Hi! We are just checking to see if the repo is still actively maintained?

thanks!

Querying with selectors?

Before I write something myself, is there an existing library somewhere to query the svgson tree using CSS-like selectors?

Example:

const rects = querySelector('#namedGroup rect')
rects.forEach(rect => {
    rect.attributes.fill = 'red'
})

main source file

I am new to this library and I want to know the main the file which contains all the functions such as parse and stringify, actully I wanted import these functions in other javascript file.

JSON schema?

Hello, thanks again for another fine project!! I am wondering if you have a JSON schema for the output format of the parse function?

Special characters generate weird CDATA tag?

Hey there!

I am currently trying to use svgson to do some bulk operations on some icons.

The source SVG includes <title>Aerom&#233;xico</title>, but when running this through svgson, it returns <title><![CDATA[Aerom&#233;xico]]></title> which causes further issues due to not being a valid HTML tag.

Is there any way to fix this?

Keep default values

I just found out that all default values are removed when the SVG is converted. I.e. if I have a stroke-width="1" im my SVG this is not in the JSON representation of this SVG. That way this can't be further used in a build i.e. for an icon sprite.
Can we introduce an option to keep all attributes, even if they have the default value? That would be awesome :)

Is it possible to promisify svgson?

Hey,
great library,
I just ran into it today :)

Is it possible to promisify svgson method when working with nodejs?

it will for sure have a good use for it

thanx for sharing 👍 👍 👍

svgson is not a function

Having problems with the Usage example:

const svgson = require('svgson');

svgson(`
  <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));
  })

Returns: TypeError: svgson is not a function

Though console logging svgson gives:

{ default: [Function: svgson],
  stringify: [Function: stringify],
  parse: [Function: svgson],
  parseSync: [Function: svgsonSync] }

Calling with svgson.default('<svg>') works.

Environment:
node: 10.16.0
npm: 6.9.0

Updating svgo to latest

Currently svgson uses [email protected] by updating to the latest version of 1.0.5 it'd be possible to use convertShapeToPath with circles.

I was trying to merge multiple paths to a single one, when realizing a circle shape is causing problems.

Set required version of `svgo` as at least 1.3.2

There's an issue with svgo which was fixed in 1.3.2: svg/svgo#1174

Our project currently needs to add "resolutions": { "svgo": "1.3.2" } to package.json when using svgson which is only supported by yarn. Since svgson is our direct requirement, this could be avoided if you made a release with this change and we set that release as a direct minimal requirement.

stringify:: Having & symbol rendered in text?

I'm manipulating text content with svgson, and occasionally the replacement copy includes & symbol.

what happens:
If there is & symbol in the text value the whole block is converted into CDATA

While the escape function for attributes is overridable, the text part is not. The escapeText function prevents the insertion of & or & symbol.

return /[&<>]/.test(str) ? // string escaped into cdata : // string raw pass

I would propose to update the regex so HTML entities like &#\d+; and &\w+; are allowed.

import files from src folder

I want to import the svgson file and use the function parse but without using node js but using statically as ES6 module is it possible, like I tried using the same but I couldn't able to do it as I am getting errors like parse is not defined...
Thanking you.

Remove omit-deep dep?

Use our own function to remove the parent prop, e.g.

export const removeAttrs = (obj) => {
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
      obj[i] = removeAttrs(obj[i])
    }
    return obj
  }

  Object.getOwnPropertyNames(obj).forEach((key) => {
    if (key === 'parent') delete obj.parent
    if (obj[key] && typeof obj[key] === 'object') removeAttrs(obj[key])
  })

  return obj
}

The omit-deep package has dependencies itself, namely https://www.npmjs.com/package/unset-value , and that package had some security audit/warnings recently. It has been updated but do we need all the other packages to remove the parent property?

I'm not exactly sure why we need to remove it in first place?

Order of SVG elements

For a SVG order of the elements is important. On the other side as per ECMAScript standards, a js object doesn't guarantee the key order. So does this library maintains the order of SVG elements?

_svgson.default.parse is not a function

Hello,
I figured i should update to the newest svgson, but im not able to get it to work.
I simply used yarn add svgson.

Code:

let json;
try {
  json = await svgson.parse(optimized);
}catch (error) {
  console.log(error);
}

Error:

TypeError: _svgson.default.parse is not a function

My package.json shows "svgson": "^3.0.0"

Any ideas? :)

--title in master branch

Hi, just wondering if the --title option in v2 is available in the master branch of the CLI tool? I couldn't seem to get it working

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.