Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

yahoo/serialize-javascript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Serialize JavaScript to asuperset of JSON that includes regular expressions, dates and functions.

npm VersionDependency StatusTest

Overview

The code in this package began its life as an internal module toexpress-state. To expand its usefulness, it now lives asserialize-javascript — an independent package on npm.

You're probably wondering:What aboutJSON.stringify()!? We've found that sometimes we need to serialize JavaScriptfunctions,regexps,dates,sets ormaps. 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. But this module is also great for communicating between node processes.

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 characters and JavaScript line terminators are escaped automatically.

Please note that serialization for ES6 Sets & Maps requires support forArray.from (not available in IE or Node < 0.12), or anArray.from polyfill.

Installation

Install using npm:

$ npm install serialize-javascript

Usage

varserialize=require('serialize-javascript');serialize({str  :'string',num  :0,obj  :{foo:'foo'},arr  :[1,2,3],bool :true,nil  :null,undef:undefined,inf  :Infinity,date :newDate("Thu, 28 Apr 2016 22:02:17 GMT"),map  :newMap([['hello','world']]),set  :newSet([123,456]),fn   :functionecho(arg){returnarg;},re   :/([^\s]+)/g,big  :BigInt(10),url  :newURL('https://example.com/'),});

The above will produce the following string output:

'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"undef":undefined,"inf":Infinity,"date":new Date("2016-04-28T22:02:17.000Z"),"map":new Map([["hello","world"]]),"set":new Set([123,456]),"fn":function echo(arg) { return arg; },"re":new RegExp("([^\\\\s]+)", "g"),"big":BigInt("10"),"url":new URL("https://example.com/")}'

Note: to produce a beautified string, you can pass an optional second argument toserialize() 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"}'

You can pass an optionalunsafe argument toserialize() for straight serialization.

Options

Theserialize() function accepts anoptions object as its second argument. All options are being defaulted toundefined:

options.space

This option is the same as thespace argument that can be passed toJSON.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 toserialize() 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});

options.unsafe

This option is to signalserialize() that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set totrue. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own.

serialize(obj,{unsafe:true});

options.ignoreFunction

This option is to signalserialize() that we do not want serialize JavaScript function.Just treat function likeJSON.stringify do, but other features will work as expected.

serialize(obj,{ignoreFunction:true});

Deserializing

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

functiondeserialize(serializedJavascript){returneval('('+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 theLICENSE file for license text and copyright information.

About

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

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors27


[8]ページ先頭

©2009-2025 Movatter.jp