All Projects → yahoo → Serialize Javascript

yahoo / Serialize Javascript

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

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Serialize Javascript

Kakajson
Fast conversion between JSON and model in Swift.
Stars: ✭ 867 (-64.36%)
Mutual labels:  json, serialize
Dataset Serialize
JSON to DataSet and DataSet to JSON converter for Delphi and Lazarus (FPC)
Stars: ✭ 213 (-91.25%)
Mutual labels:  json, serialize
Jc
CLI tool and python library that converts the output of popular command-line tools and file-types to JSON or Dictionaries. This allows piping of output to tools like jq and simplifying automation scripts.
Stars: ✭ 967 (-60.25%)
Mutual labels:  json, serialize
Ason
[DEPRECATED]: Prefer Moshi, Jackson, Gson, or LoganSquare
Stars: ✭ 777 (-68.06%)
Mutual labels:  json, serialize
Javascript Stringify
Stringify is to `eval` as `JSON.stringify` is to `JSON.parse`
Stars: ✭ 98 (-95.97%)
Mutual labels:  json, serialize
Csmodel
CSModel is a concise and efficient model framework for iOS/OSX, and provides nested Model to compare values and copy values.
Stars: ✭ 192 (-92.11%)
Mutual labels:  json
Cti Python Stix2
OASIS TC Open Repository: Python APIs for STIX 2
Stars: ✭ 194 (-92.03%)
Mutual labels:  json
Jsonapi Utils
Build JSON API-compliant APIs on Rails with no (or less) learning curve.
Stars: ✭ 191 (-92.15%)
Mutual labels:  json
Hjson
Hjson, a user interface for JSON
Stars: ✭ 2,330 (-4.23%)
Mutual labels:  json
Discovery
Frontend framework for rapid data (JSON) analysis, sharable serverless reports and dashboards
Stars: ✭ 199 (-91.82%)
Mutual labels:  json
Jsonform
Build forms from JSON Schema. Easily template-able. Compatible with Bootstrap 3 out of the box.
Stars: ✭ 2,416 (-0.7%)
Mutual labels:  json
Swagger Toolbox
💡 Swagger schema model (in yaml, json) generator from json data
Stars: ✭ 194 (-92.03%)
Mutual labels:  json
Bridge.
Minecraft Add-on Editor | We strive to provide the best development experience possible
Stars: ✭ 193 (-92.07%)
Mutual labels:  json
Jsonframe Cheerio
simple multi-level scraper json input/output for Cheerio
Stars: ✭ 196 (-91.94%)
Mutual labels:  json
Json Schema Spec
The JSON Schema I-D sources
Stars: ✭ 2,441 (+0.33%)
Mutual labels:  json
Xlog
Android logger, pretty, powerful and flexible, log to everywhere, save to file, all you want is here.
Stars: ✭ 2,468 (+1.44%)
Mutual labels:  json
Mtgjson
MTGJSON build scripts for Magic: the Gathering
Stars: ✭ 191 (-92.15%)
Mutual labels:  json
Sdk
Library for using Grafana' structures in Go programs and client for Grafana REST API.
Stars: ✭ 193 (-92.07%)
Mutual labels:  json
Hana
An implementation of JSON Patch and JSON Pointer
Stars: ✭ 196 (-91.94%)
Mutual labels:  json
Mxisd
Federated Matrix Identity Server
Stars: ✭ 194 (-92.03%)
Mutual labels:  json

Serialize JavaScript

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

npm Version Dependency Status Test

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, regexps, dates, sets or maps. 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 for Array.from (not available in IE or Node < 0.12), or an Array.from polyfill.

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,
    inf  : Infinity,
    date : new Date("Thu, 28 Apr 2016 22:02:17 GMT"),
    map  : new Map([['hello', 'world']]),
    set  : new Set([123, 456]),
    fn   : function echo(arg) { return arg; },
    re   : /([^\s]+)/g,
    big  : BigInt(10),
});

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")}'

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"}'

You can pass an optional unsafe argument to serialize() for straight serialization.

Options

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});

options.ignoreFunction

This option is to signal serialize() that we do not want serialize JavaScript function. Just treat function like JSON.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:

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].