Giter Club home page Giter Club logo

serialize-javascript's Introduction

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),
    url  : new URL('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 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.

serialize-javascript's People

Contributors

caridy avatar dependabot-preview[bot] avatar dependabot[bot] avatar eddyerburgh avatar ericf avatar ethanresnick avatar hekike avatar jackstevenson avatar jowenjowen avatar kwolfy avatar mkanyar avatar momocow avatar mum-never-proud avatar nicojs avatar nqdy666 avatar okuryu avatar pimterry avatar piwysocki avatar realdennis avatar redonkulus avatar rrdelaney avatar siebes avatar styfle avatar victorporof avatar vthibault 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  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

serialize-javascript's Issues

key filter support?

I want to ignore all keys starting with _ when serializing. Will it be implemented?

Support for instances of classes

I am working on an implementation for supporting instances of classes. For example:

class Person {
  constructor(name, parent) {
    this.name = name;
    this.parent = parent;
  }
}

serialize(new Person('foo', new Person('bar', null)); 
// => 'new Person("foo", new Person("bar", null))'

Would you guys be interested in this kind of functionality?

Version 3.1.0 is not working in React-Native when is not in debugging mode or when is generating release

Hello, I'm using serialize-javascript in React-Native instead of JSON.stringify function. The version 3.1.0 is not working in React-Native when the debugger is off or in the release apk (because there is no debugger).

The issue is:
Error: Secure random number generation is not supported by this browser. Use Chrome, Firefox or Internet Explorer 11.

Reproduce:

  1. In React-Native project install with npm, npx or yarn the package serialize-javascript.
  2. Create a serialize function:
import serializeJs from 'serialize-javascript';
...

const clearArrayUndefinedValues = (array) => {
 try {
   if (!Array.isArray(array))
     throw new Error('Invalid argument. Must be an array.');

   const filteredArr = array.reduce((arr, current) => {
     if (typeof current === 'object' && current !== null) {
       if (Array.isArray(current))
         return [...arr, clearArrayUndefinedValues(current)];
       // eslint-disable-next-line no-use-before-define
       return [...arr, clearObjectUndefinedValues(current)];
     } else if (current !== undefined) return [...arr, current];

     return arr;
   }, []);

   return filteredArr;
 } catch (error) {
   console.log(
     '##\t Error log in clearArrayUndefinedValues on app/shared/utils.js ->',
     error
   );
   return null;
 }
};

const clearObjectUndefinedValues = (object) => {
 try {
   if (typeof object !== 'object')
     throw new Error('Invalid argument. Must be an object.');

   if (object === null) throw new Error('Invalid argument. Must not be null.');

   const filtered = Object.keys(object).reduce((obj, key) => {
     const { [key]: current } = object;

     if (typeof current === 'object' && current !== null) {
       if (Array.isArray(current))
         return { ...obj, [key]: clearArrayUndefinedValues(current) };

       return { ...obj, [key]: clearObjectUndefinedValues(current) };
     } else if (current !== undefined) return { ...obj, [key]: current };

     return obj;
   }, {});

   return filtered;
 } catch (error) {
   console.log(
     '##\t Error log in clearObjectUndefinedValues on app/shared/utils.js ->',
     error
   );
   return null;
 }
};

export const serialize = (object) => {
 try {
   if (typeof object !== 'object')
     throw new Error('Invalid argument. Must be an object.');

   if (object === null) throw new Error('Invalid argument. Must not be null.');

   if (Array.isArray(object))
     return serializeJs(clearArrayUndefinedValues(object));

   return serializeJs(clearObjectUndefinedValues(object));
 } catch (error) {
   console.log('##\t Error log in serialize on app/shared/utils.js ->', error);
   return null;
 }
};
  1. Use a serialize function in any place of your code:
import { serialize } from '../shared/utils';
...
const  JSONToObject = serialize(data);

My set is:

MacOs 10.15.5
i7 2.2Ghz
16GB

Running app in simulators:

iPhone 11 os 13.5
Pixel 3 os Android API 29.

Chrome version:

83.0.4103.61 64 bits

The previous version (3.0.0) working well. There are a prevision/way to fix this to work without debugger?

Document breaking change for 2.0.0

The release notes for 2.0.0 only mention a PR which references another issue that I think means this version will include undefined values in the output while it didn't before.

It would be helpful to have a clear indication of what the breaking change for the major version is in the releases list.

feat: option to inject code verbatim

It would be handy for a use case I have for this package to support a feature that could inject code verbatim if it appears in a JavaScript object.

To implement, we could use (A) a special object constructor, (B) a special property on a string, or (C) a tagged template literal returning some special value, which would allow us to detect such cases in the serialization code.

A:

const object = {
  customCode: serialize.verbatim('window.navigator.userAgent')
};

B:

const customCode = 'window.navigator.userAgent';
customCode.verbatim = true;
const object = {
  customCode
};

C:

const customCode = serialize.verbatim`window.navigator.userAgent`;
const object = {
  customCode
};

I tried a hack similar to #32 (comment) using a function as a value and overriding its toString method, but it didn't work since I can't include ( in the code without it being rewritten as part of the function serialization.

It's possible to turn a string into a function

If the attacker controls a string and there's a function in the same serialization process, then he is going to be able to convert its string as a function.

var serialize = require('serialize-javascript');
console.log(serialize({a: function() {}, b: '@__FUNCTION_0__@'}));
{
  "a": function () {},
  "b": function () {}
}

It seems unlikely that it is possible to exploit it, but we never know.

In the same vein, an attacker can throw an exception if it is given a string and there's a function serialized somewhere.

var serialize = require('serialize-javascript');
console.log(serialize({a: function() {}, b: '@__FUNCTION_999__@'}));
serialize/node_modules/serialize-javascript/index.js:80
            serializedFn = fn.toString();
                             ^
TypeError: Cannot read property 'toString' of undefined
    at serialize/node_modules/serialize-javascript/index.js:80:30
    at String.replace (native)
    at serialize (serialize/node_modules/serialize-javascript/index.js:74:16)
    at Object.<anonymous> (serialize/test.js:2:13)
    at Module._compile (module.js:430:26)
    at Object.Module._extensions..js (module.js:448:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:471:10)
    at startup (node.js:117:18)

BigInt not supported but it has been since v4

Node 16.0.0
Serialize-Javascript 6.0.0
Typescript 4.3.4

I ran into this error today, my first idea is that "BigInt" is weird because I'm using typescript?

Example data: { big: BigInt(0) }

Error:

str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
                   ^
TypeError: Do not know how to serialize a BigInt

Collaborating with JSON5

There is a group of people on GitHub trying to draft a new standard of JSON called JSON5.
It might be a good idea to take a look at it and see if there are ways of improving it.
see: json5/json5#190

Uncaught TypeError: Serializing native function: click

I am getting this error, what does it mean?

index.js?f653:111 Uncaught TypeError: Serializing native function: click
    at serializeFunc (index.js?f653:111)
    at eval (index.js?f653:208)
    at String.replace (<anonymous>)
    at serialize (index.js?f653:185)
    at Function.serialize (_.js?edd5:56)
    at eval (skeleton.mixin.js?d550:233)

Version 1.6.0 on NPM is not valid ES5 code

AFAIR the public npmjs.com repository requires packages to be valid ES5 code. Apparently serialize-javascript is not ES5 since 1.6.0 version. Steps to reproduce:

npm i [email protected]
npm i es-check --save-dev
./node_modules/.bin/es-check es5 'node_modules/serialize-javascript/*.js'

For version 1.5.0 the above does not complain at all.

My specific case was that UglifyJs babel plugin complains about not being able to compile JS code during build process once serialize-javascript got upgraded to 1.6.0 version.

Is escaping '>' necessary?

I am wondering if you cannot save a few cycles and bytes by not escaping >. As far as I can tell, is has no influence on <script> termination?

Shorthand method definition fails to serialize and eval property

*properly

When using shorthand to define a function as a method in an object literal, serialization assigns a named function expression, which fails to evaluate.

$ var testSer = {  fn1: function(a) { console.log(a); return this; }, fn2: (d) => { console.log(d); return this; }, fn3(r) { console.log(r); return this; } };

Validate the functions first:


 test 1
{ fn1: [Function], fn2: [Function], fn3: [Function: fn3] }

$ testSer.fn2('test 2')

test 2
<context>

$ testSer.fn3('test 3')

test 3
{ fn1: [Function], fn2: [Function], fn3: [Function: fn3] }

Do the serialization:


$ ca
'{"fn1":function (a) { console.log(a); return this; },"fn2":(d) => { console.log(d); return this; },"fn3":fn3(r) { console.log(r); return this;  }}'

Note how it has created a "fn3" entry as a named function, but has neglected to add the function keyword.

Now try to eval:

$ var c = eval('('+ca+')');

SyntaxError: Unexpected token {
  at repl:1:20
  at REPLServer.defaultEval (repl.js:262:27)
  at bound (domain.js:287:14)
  at REPLServer.runBound [as eval] (domain.js:300:12)
  at REPLServer.<anonymous> (repl.js:431:12)
  at emitOne (events.js:82:20)
  at REPLServer.emit (events.js:169:7)
  at REPLServer.Interface._onLine (readline.js:211:10)
  at REPLServer.Interface._line (readline.js:550:8)
  at REPLServer.Interface._ttyWrite (readline.js:827:14)
  at ReadStream.onkeypress (readline.js:106:10)
  at emitTwo (events.js:87:13)
  at ReadStream.emit (events.js:172:7)
  at emitKeys (readline.js:1251:14)
  at next (native)
  at ReadStream.onData (readline.js:919:36)
  at emitOne (events.js:77:13)
  at ReadStream.emit (events.js:169:7)
  at readableAddChunk (_stream_readable.js:153:18)
  at ReadStream.Readable.push (_stream_readable.js:111:10)
  at TTY.onread (net.js:531:20)

All it needs to do is add the function keyword:

'{"fn1":function (a) { console.log(a); return this; },"fn2":(d) => { console.log(d); return this; },"fn3": function fn3(r) { console.log(r); return this;  }}'

Node version:

$ node -v
  v4.4.3

Pass/Define `space` attribute

It's impossible to change space value in JSON.stringify method,

It's just hardcoded

var SPACE = 2;

module.exports = function serialize(obj) {
    /* ... */
    str = JSON.stringify(obj, function (key, value) {
    /* ... */
    }, SPACE);

extract same refs of object

It's very nice if support extracting same refs of object, for example

var obj = {}
serialize({b: obj, c: obj})

get

(function() { var a = {}; return {"b": a, "c": a} })()

Support custome object

Add support for serialization and deserialization of custom objects via Object.assign and Object.create
For example:

class A {
    a = 1
}
serialize(A, { classes: { A } })

get

const serialized = "(function(args) {var k = args[0].classes;return args[0].assign(Object.create(k.A.prototype), { a: 1 })})(arguments)"
function unserialize() {
    return eval(serialized)
}
unserialize({ classes: {A: function() {}}, assign: Object.assign })

Line returns added in serialized function when running through jest

I always get the weirdest issues. So, serialize-javascript works fine in actual production, but it somehow outputs a different thing while running a test. In the example of the object with all the types including the function, I get an odd line return within the serialized function.

Environment:

  • Node 14.13.0
  • Jest 26.5.2
  • serialize-javascript 5.0.1

Reproduction:
(Alternatively, see https://gist.github.com/eslachance/6dbd88820f09de4509d4f19c4c0e7ad6 for reproduction)

  • Create a jest test
  • import serialize-javascript
  • Add a console.log of the serialized example.
test("serializes javascript", () => {
  console.log(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),
  }))
});

Expected result:

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

Actual Result:

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

The expected result was a simple nodejs file which outputs the serialized data and nothing else.

This is confusing me very much, and I don't know where to begin in troubleshooting it.

Add prettify option

serialize({
  foo: 12.4,
  bar: "echo",
  baz: function() {
    return true
  }
}, 2);

output:

{
  "foo": 12.4,
  "bar": "echo",
  "baz": function(){ return true }
}

Symbols

I'm not sure if you want to have symbols as part of this or not

{
  [Symbol('foo')]: Symbol('bar')
}

Deserialize support?

How would one go about deserializing a serialized string? I want to use this library to serialize objects that might contain regex's and pass them on to a child process using childProcess.send. Therefore i need to deserialize on the other end.

Is this a use case that this library should support? Or is that something that should be done somewhere else?

I guess i could use something like this:

function deserialize(serializedData){
  require('vm').runInThisContext('var a = ' + serializedData);
  return a;
}

But i don't think its elegant.

Thanks in advance!

Split responsibilities

Just a quick thought I had when I read the changelog for 1.3.0: To me it seems to have two responsibilities and as such violate the SRP:

  1. prevent security issues by espacing unsafe characters
  2. serialize data that is not compatible with JSON

Instead of having a isJSON flag that controls wether one of those functionalities should be ignored, there could be two functions:

const escapeUnsafe = (o) => ...
const serializeNonJSON = (o) => 

And a function that has the current behaviour could simply be composed of those functions:

const serializeJavascript = compose(escapeUnsafe, serializeNonJSON);

(For performance reasons a different implementation may be necessary in JS of course)

ES6 & standardJS syntax

I'd love an option to render functions in modern ES6 and standardJS syntax.

Eg. instead of

const echo = function (arg) { return arg; }

I'd want

const echo = arg => arg

standardJS is about small details like single vs double quotes, no semicolons, etc.

Unexpected regular expression

Input:

const options = {
      file: 'test5.js',
      input: '/******/ function hello(a) {console.log(a)}',
      terserOptions: {
        output: {
          comments: 'all',
        },
      },
      extractComments: {
        condition: 'should be extracted',
        filename: (file) => file.replace(/(\.\w+)$/, '.license$1'),
        banner: (licenseFile) =>
          `License information can be found in ${licenseFile}`,
      },
    }

After serialize we use

const options = new Function(
      'exports',
      'require',
      'module',
      '__filename',
      '__dirname',
      `'use strict'\nreturn ${options}`
    )(exports, require, module, __filename, __dirname);

And code in Function throw SyntaxError: Unexpected regular expression

Manually fixing vulnerabilitites

Following pkgs were installed:
↳ npm add netlify-cms gridsome-plugin-netlify-cms @gridsome/source-filesystem @gridsome/transformer-remark

Vulnerabilitites:
found 2 vulnerabilities (1 moderate, 1 high)

Failed to fix:
↳ npm audit fix

Ran this & report attached:
↳ npm audit

serialize-javascript versions installed & failed:

5.0.1, 3.1.0, 4.0.0
Screenshot at 2021-01-05 14-43-41

Can't used in browser?

I want to use serialize-javascript in vite project.
There are two problem,At first buffer is undefined,I install buffer,and then there is an error at randombytes,the error code is here:

//randombytes/browser.js
var crypto = global.crypto || global.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}
.........

In browser,global is undefined!
I try to change it as this:

const globalThis = typeof global === 'object' ? global : window;

var crypto = globalThis.crypto || globalThis.msCrypto

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}

And then,serialize-javascript wrok!

slow serialization for some cases (happens in Node.js 10)

Hi @ericf as we discussed, there might be some case to cause a GC pause,

I'm guessing it's some V8 de-opt we're hitting because the replacer forces V8 to go from native-land to user-land and back. Whereas with JSON.stringify().replace() it can stay in native-land the whole time.
So it's probably causing a serialization/de-serialization of the massive string causing a GC pause.

Now we have data ~500KB to be serialized, and found that some case(typically when the data is complicated and big enough) str.replace takes a very long time after JSON.stringify with replacer

To reproduce it, here's the simple script with the data we have,
We will get rid of it with a gc() or run without replacer, it acts like what you mentioned.
https://drive.google.com/file/d/0B0ZB5_LvayjrRjV0U2hrMGVjMUE/view?usp=sharing
please run node --trace-gc --replacer --issue ./slowserialization.js to reproduce it and see gc solve it with node --trace-gc --expose-gc --replacer --issue --gc ./slowserialization.js

will see when slow serialization happens, there's a lot of sweep and cause time spend.

[41363]     3133 ms: Mark-sweep 331.0 (368.4) -> 327.2 (366.4) MB, 123 ms [last resort gc].
[41363]     3249 ms: Mark-sweep 327.2 (366.4) -> 327.2 (364.4) MB, 116 ms [last resort gc].
[41363]     3361 ms: Mark-sweep 327.2 (364.4) -> 327.2 (364.4) MB, 112 ms [last resort gc].
[41363]     3475 ms: Mark-sweep 327.2 (364.4) -> 327.2 (364.4) MB, 113 ms [last resort gc].
[41363]     3578 ms: Mark-sweep 327.2 (364.4) -> 327.2 (364.4) MB, 103 ms [last resort gc].
[41363]     3676 ms: Mark-sweep 327.2 (364.4) -> 327.2 (364.4) MB, 97 ms [last resort gc].
[41363]     3776 ms: Mark-sweep 327.2 (364.4) -> 327.2 (364.4) MB, 100 ms [last resort gc].

The slow serialization only happens with Node.js 10, 12 won't have that issue.

I don't think that makes sense to fix this only for Node.js 10, but let's discuss here, like can we try something else for handling the function/regexp or make that optional (for our main customer's case, we don't have function and regexp)?

@redonkulus @lingyan @mridgway @Vijar

Unable to resolve module `buffer` in react-native

Packages

  • react-native: 0.63.2
  • serialize-javascript: 3.1.0 and higher (3.1.0 - 5.1.0)

Use

import serialize from 'serialize-javascript'

...

const var1 = serialize(value)

Error
The application crashes on startup with an error:
Unable to resolve module buffer from node_modules/safe-buffer/index.js: buffer could not be found within the project

Found a solution (in App.js):
npm install -S buffer

import { Buffer } from 'buffer';
global.Buffer = Buffer; // very important

But that doesn't work either and throws another error:

  • ERROR Error: Secure random number generation is not supported by this browser.
    Use Chrome, Firefox or Internet Explorer 11
  • ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

v1.9.0 creates invalid json by including undefined values

There seems to be a regression in v1.9.0 where objects with undefined values are being included in the json output, which is invalid. For example:

serialize({
  "foobar": undefined
});

Output:

{"foobar":undefined}

This is not valid json, and will fail when run through JSON.parse()

In v1.8.0 this worked correctly with the following output:

{}

How to use in the browser

I thought it'd be easy to use serialize-javascript in the browser but I'm obviously doing something wrong.

I created an index.js which contains a single line

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

Then I installed browserify (sudo npm install browserify -g), installed serialize-javascript (npm install serialize-javascript) and ran browserify index.js > serialize-javascript.js.

After I load serialize-javascript.js in the browser there's no serialize() function available.

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.