Git Product home page Git Product logo

serialize-javascript's Introduction

Serialize JavaScript

Serialize JavaScript to a superset of JSON that includes regular expressions and functions.

npm Version Dependency Status Build Status

Overview

The code in this package began its life as an internal module to express-state. To expand its usefulness, it now lives as serialize-javascript โ€” an independent package on npm.

You're probably wondering: What about JSON.stringify()!? We've found that sometimes we need to serialize JavaScript functions and regexps. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client.

The string returned from this package's single export function is literal JavaScript which can be saved to a .js file, or be embedded into an HTML document by making the content of a <script> element. HTML charaters and JavaScript line terminators are escaped automatically.

Installation

Install using npm:

$ npm install serialize-javascript

Usage

var serialize = require('serialize-javascript');

serialize({
    str  : 'string',
    num  : 0,
    obj  : {foo: 'foo'},
    arr  : [1, 2, 3],
    bool : true,
    nil  : null,
    undef: undefined,

    fn: function echo(arg) { return arg; },
    re: /([^\s]+)/g
});

The above will produce the following string output:

'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"fn":function echo(arg) { return arg; },"re":/([^\\s]+)/g}'

Note: to produced a beautified string, you can pass an optional second argument to serialize() to define the number of spaces to be used for the indentation.

Automatic Escaping of HTML Characters

A primary feature of this package is to serialize code to a string of literal JavaScript which can be embedded in an HTML document by adding it as the contents of the <script> element. In order to make this safe, HTML characters and JavaScript line terminators are escaped automatically.

serialize({
    haxorXSS: '</script>'
});

The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate:

'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}'

Options

The serialize() function accepts options as its second argument. There are two options, both default to being undefined:

options.space

This option is the same as the space argument that can be passed to JSON.stringify. It can be used to add whitespace and indentation to the serialized output to make it more readable.

serialize(obj, {space: 2});

options.isJSON

This option is a signal to serialize() that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up.

Note: That when using this option, the output will still be escaped to protect against XSS.

serialize(obj, {isJSON: true});

Deserializing

For some use cases you might also need to deserialize the string. This is explicitely not part of this module. However, you can easily write it yourself:

function deserialize(serializedJavascript){
  return eval('(' + serializedJavascript + ')');
}

Note: Don't forget the parentheses around the serialized javascript, as the opening bracket { will be considered to be the start of a body.

License

This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.

serialize-javascript's People

Contributors

ericf avatar caridy avatar nicojs avatar hekike avatar

Watchers

Endrigo Antonini avatar

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.