Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
serialize-javascript
Advanced tools
Serialize JavaScript to a superset of JSON that includes regular expressions and functions.
The serialize-javascript npm package is used to serialize JavaScript to a superset of JSON that includes regular expressions, dates, and functions. It is typically used to safely pass data from a server to a client-side script.
Serialize Data
This feature allows the serialization of JavaScript objects, including those containing Dates, RegExps, and functions, into a string format that can be safely transported over a network and then re-evaluated or parsed on the client side.
const serialize = require('serialize-javascript');
const user = { name: 'Alice', email: 'alice@example.com', lastLogin: new Date() };
const serializedUser = serialize(user);
Serialize with Options
This feature allows customization of the serialization process with options such as indentation for pretty-printing the serialized string.
const serialize = require('serialize-javascript');
const user = { name: 'Alice', email: 'alice@example.com', lastLogin: new Date() };
const serializedUser = serialize(user, { space: 2 });
Serialize Including Functions
This feature allows the serialization of functions within objects by setting the 'isJSON' option to false, which enables the inclusion of non-JSON-safe features in the serialized string.
const serialize = require('serialize-javascript');
const user = { greet() { return 'Hello!'; } };
const serializedUser = serialize(user, { isJSON: false });
Flatted is a package similar to serialize-javascript that can serialize and deserialize data containing circular references. Unlike serialize-javascript, it does not handle functions or regexes but is specifically designed to work with circular data structures.
JSAN is a JSON-like serializer that can handle circular references, functions, and other non-JSON data types. It is similar to serialize-javascript but uses a different approach to encode non-standard JSON types.
This package provides a way to safely stringify objects with circular references, similar to serialize-javascript. It does not handle functions or regexes and focuses on preventing circular reference errors during JSON serialization.
Serialize JavaScript to a superset of JSON that includes regular expressions, dates and functions.
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, regexps or dates. 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.
Install using npm:
$ npm install serialize-javascript
var serialize = require('serialize-javascript');
serialize({
str : 'string',
num : 0,
obj : {foo: 'foo'},
arr : [1, 2, 3],
bool : true,
nil : null,
undef: undefined,
date: new Date("Thu, 28 Apr 2016 22:02:17 GMT"),
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,date:new Date("2016-04-28T22:02:17.156Z"),"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.
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 optional
unsafe
argument toserialize()
for straight serialization.
The serialize()
function accepts an options
object as its second argument. All options are being defaulted to 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});
options.unsafe
This option is to signal serialize()
that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to true
. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own.
serialize(obj, {unsafe: true});
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:
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.
This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.
FAQs
Serialize JavaScript to a superset of JSON that includes regular expressions and functions.
The npm package serialize-javascript receives a total of 21,592,339 weekly downloads. As such, serialize-javascript popularity was classified as popular.
We found that serialize-javascript demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.