Giter Club home page Giter Club logo

serialize-to-js's Introduction

serialize-to-js

serialize objects to javascript

NPM version Build Status

Serialize objects into a string while checking circular structures and respecting references.

The following Objects are supported

  • String
  • Number
  • Boolean
  • Object
  • Array
  • RegExp
  • Error
  • Date
  • Buffer
  • Int8Array, Uint8Array, Uint8ClampedArray
  • Int16Array, Uint16Array
  • Int32Array, Uint32Array, Float32Array
  • Float64Array
  • Set
  • Map

Table of Contents

Methods

serialize

serialize(source, opts, opts.ignoreCircular, opts.reference)

serializes an object to javascript

Example - serializing regex, date, buffer, ...

const serialize = require('serialize-to-js')
const obj = {
  str: '<script>var a = 0 > 1</script>',
  num: 3.1415,
  bool: true,
  nil: null,
  undef: undefined,
  obj: { foo: 'bar' },
  arr: [1, '2'],
  regexp: /^test?$/,
  date: new Date(),
  buffer: new Buffer('data'),
  set: new Set([1, 2, 3]),
  map: new Map([['a': 1],['b': 2]])
}
console.log(serialize(obj))
//> '{str: "\u003Cscript\u003Evar a = 0 \u003E 1\u003C\u002Fscript\u003E",
//>   num: 3.1415, bool: true, nil: null, undef: undefined,
//>   obj: {foo: "bar"}, arr: [1, "2"], regexp: new RegExp("^test?$", ""),
//>   date: new Date("2019-12-29T10:37:36.613Z"),
//>   buffer: Buffer.from("ZGF0YQ==", "base64"), set: new Set([1, 2, 3]),
//>   map: new Map([["a", 1], ["b", 2]])}'

Example - serializing while respecting references

var serialize = require('serialize-to-js')
var obj = { object: { regexp: /^test?$/ } };
obj.reference = obj.object;
var opts = { reference: true };
console.log(serialize(obj, opts));
//> {object: {regexp: /^test?$/}}
console.log(opts.references);
//> [ [ '.reference', '.object' ] ]

Parameters

source: Object | Array | function | Any, source to serialize
opts: Object, options
opts.ignoreCircular: Boolean, ignore circular objects
opts.reference: Boolean, reference instead of a copy (requires post-processing of opts.references)
opts.unsafe: Boolean, do not escape chars <>/
Returns: String, serialized representation of source

Contribution and License Agreement

If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work or correctly attributed with the source of its origin and licence.

License

Copyright (c) 2016- commenthol (MIT License)

See LICENSE for more info.

serialize-to-js's People

Contributors

commenthol 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

Watchers

 avatar  avatar  avatar  avatar  avatar

serialize-to-js's Issues

SyntaxError: Unexpected token {

Code:

const lib = require('serialize-to-js');

const testData = {
  mtd(arg) { return arg },
};

const serializedData = lib.serialize(testData);
const deserializeData = lib.deserialize(serializedData, true);

console.log(testData);
console.log(deserializeData);

We want to migrate from serialize-javascript (https://github.com/yahoo/serialize-javascript) in webpack to your library. Two blokers:

  • This issue
  • #7

Type declaration

Hi,

There's no third-party types available for this package, so I had to add my own:

declare module "serialize-to-js" {
  export = serialize;

  function serialize(source: any, options?: { ignoreCircular?: boolean, reference?: boolean, unsafe?: boolean }): string;
}

I'm honestly not an expert in this area, but putting this in a serialize-to-js.d.ts file in the root of my project worked - you could probably just dump this as index.d.ts in the root folder and the package would have type-checking in TS and auto-completions in VS Code and other editors.

Cheers ๐Ÿ™‚

Can't resolve 'safer-eval'

Since updating to v1.1.0 I'm getting this issue whilst building.

ERROR in ./~/serialize-to-js/lib/deserialize.js
Module not found: Error: Can't resolve 'safer-eval' in '~/Code/thingy/node_modules/serialize-to-js/lib'
 @ ./~/serialize-to-js/lib/deserialize.js 9:16-37
 @ ./~/serialize-to-js/lib/index.js
 @ ./app/views/PrintView.js
 @ ./app/routes.js
 @ ./app/app.js
 @ ./app/index.js
 @ multi webpack-hot-middleware/client?reload=true ./app

Resolved it for now by downgrading to v1.0.0

Using Node v6.9.1 with NPM v3.10.8 on macOS 10.12.3

Support for functions

Are functions supported at all? What happens when a property value is a function?

References in Map

Hi! This seems like a really promising library for debugging complex JS applications :) Or serialising complex JS objects.

In our code, we often use Map, but references in there get copied by value. Is there a way to generate JS code that will construct the full JS object?

var serialize = require('serialize-to-js')

var fooBar = {foo:"bar"}

let m = new Map()
m.set('key1', fooBar)
m.set('key2', fooBar)

var obj = {
  ref1: fooBar,
  ref2: fooBar,
  ref3: fooBar,
  m: m,
}

var opts = { reference: true }
var withoutRefs = serialize(obj, opts)
console.log(opts.references)

var refsCode = "var tmp = " + withoutRefs + ";\n"
for(var i = 0; i < opts.references.length; i+= 1){
    var entry = opts.references[i];
    refsCode += "tmp" + entry[0] + " = tmp" + entry[1] + ";\n"
}
console.log(refsCode)
// var tmp = {ref1: {foo: "bar"}}
// tmp.ref2 = tmp.ref1;
// tmp.ref3 = tmp.ref1;
// The refs in the map are missing :(

serialize backslash is not working properly

serialize an object {backSlash: "\\"} would result in {backSlash: "\"} which would cause error when deserialize later on. The serialize should produce {backSlash: "\\"} as in JSON.stringify.

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.