如何序列化和反序列化 Javascript 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3608545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:25:05  来源:igfitidea点击:

How to serialize & deserialize Javascript objects?

javascriptserialization

提问by Stewart Johnson

I need to serialize and deserialize Javascript objects to store them in a DB.

我需要序列化和反序列化 Javascript 对象以将它们存储在数据库中。

Note that these objects contain functions, so I can't store them as JSON, so I can't use json2.js.

请注意,这些对象包含函数,因此我无法将它们存储为 JSON,因此无法使用 json2.js。

What's the state of the art in [de]serialization of javascript objects (in javascript of course).

javascript 对象的 [反] 序列化的最新技术是什么(当然是在 javascript 中)。

Thanks, Stewart

谢谢,斯图尔特

采纳答案by Matthew Crumley

In general, there's no way (in a browser) so serialize objects with functions attached to them, since every function has a reference to it's outer scope. If the function references any of those variables, they won't exist anymore when you deserialize it.

一般来说,没有办法(在浏览器中)序列化带有附加到它们的函数的对象,因为每个函数都有对其外部作用域的引用。如果该函数引用了这些变量中的任何一个,则反序列化它时它们将不再存在。

What I would to is use the built-in (or json2.js) JSON.stringifyand JSON.parsefunctions with the replacerand reviverparameters. Here's a partial example of how it would work:

我想要的是使用内置(或 json2.js)JSON.stringifyJSON.parse带有replacerreviver参数的函数。这是它如何工作的部分示例:

JSON.stringify(yourObject, function(name, value) {
    if (value instanceof LatLng) { // Could also check the name if you want
        return 'LatLng(' + value.lat() + ',' + value.lng() + ')';
    }
    else if (...) {
        // Some other type that needs custom serialization
    }
    else {
        return value;
    }
});

JSON.parse(jsonString, function(name, value) {
    if (/^LatLng\(/.test(value)) { // Checking the name would be safer
        var match = /LatLng\(([^,]+),([^,]+)\)/.exec(value);
        return new LatLng(match[1], match[2]);
    }
    else if (...) {
        ...
    }
    else {
        return value;
    }
});

You can use any serialization format you want in your custom types. The "LatLng(latitude,longitude)" format is just one way of doing it. You could even return a javascript object that can be serialized to JSON natively.

您可以在自定义类型中使用任何您想要的序列化格式。“LatLng(latitude,longitude)”格式只是一种方法。您甚至可以返回一个可以本地序列化为 JSON 的 javascript 对象。

回答by lknox

You don't want to serialize logic such as functions.

您不想序列化诸如函数之类的逻辑。

If you have to update your logic / js functions in the future, you don't (always) want the older logic to be loaded back with the data neccessarily. Beware.

如果您将来必须更新您的逻辑/js 函数,您(总是)不希望将旧的逻辑与数据一起加载回来。谨防。

回答by Haim Evgi

use gserializer:

使用gserializer

http://www.onegeek.com.au/articles/programming/javascript-serialization.php

http://www.onegeek.com.au/articles/programming/javascript-serialization.php

the code in google :

谷歌中的代码:

http://code.google.com/p/gserializer/

http://code.google.com/p/gserializer/

GSerializer is a javascript library to serialize/deserialize javascript objects to and from strings, for persistance in say, a Cookie. Unlike many other implementations, GSerializer can also serialize functions and non-JSON notation.

GSerializer 是一个 javascript 库,用于将 javascript 对象序列化/反序列化到字符串和从字符串中序列化,例如 Cookie 的持久性。与许多其他实现不同,GSerializer 还可以序列化函数和非 JSON 符号。

回答by prototype

On Node.js, there is also the JASON package.

在 Node.js 上,还有JASON 包

Here is the example:

这是示例:

var JASON = require("JASON");

str = JASON.stringify(obj);
obj = JASON.parse(str);

Install the package by: npm install JASON.

通过以下方式安装软件包:npm install JASON

回答by Sir Robert

If you're using ES6 versions of Node, you can check out a small package I wrote called JSOFF. It's the JavaScript Object-Function Format; a drop-in replacement for JSON that handles functions.

如果您使用的是 ES6 版本的 Node,您可以查看我编写的一个名为JSOFF 的小包。它是 JavaScript 对象函数格式;处理函数的 JSON 的替代品。

It's super tiny and simple, so Babeljs or Browserify may be your friends.

它非常小巧和简单,所以 Babeljs 或 Browserify 可能是你的朋友。

Install via: npm install jsoffor yarn add jsoff.

通过以下方式安装:npm install jsoffyarn add jsoff.

Here is the example how to create an object with functions:

以下是如何使用函数创建对象的示例:

const JSOFF  = require('jsoff');

var obj = {
  abc: 123,
  def: function (a,b) { return a * 2 + b * 3; },
  ghi: a => { return a * 2 },
  jkl: (a,b) => { return ((d,e) => { return a*d + b*e })(2,4) }
};

var str = JSOFF.stringify(obj);
// str is now:  
// '{"abc":123,"def":"function (a,b) { return a * 2 + b * 3; }","ghi":"a => { return a * 2 }","jkl":"(a,b) => { return ((d,e) => { return a*d + b*e })(2,4) }"}');
});

var clone = JSOFF.parse(str);
clone.def(10,5)   // 35
clone.ghi(5)      // 10
clone.jkl(10,20)  // 100

回答by fishgen

I wouldn't serialize JS functions because of security reasons. Through a public API all kinds of nasty things could be sent to the database. As for deserialisation I've got a different approach. I'm mixing model objects defined on client side with the data coming from JSON. I have a small tool to do that, take a look at it on GitHub at khayll/jsonmix.

由于安全原因,我不会序列化 JS 函数。通过公共 API,可以将各种讨厌的东西发送到数据库。至于反序列化,我有不同的方法。我将客户端定义的模型对象与来自 JSON 的数据混合在一起。我有一个小工具可以做到这一点,请在 GitHub 上的khayll/jsonmix上查看它。

JsonMix provides a kind of deserialisation from JSON into JavaScript Objects complete with functions.

JsonMix 提供了一种从 JSON 反序列化为带有函数的 JavaScript 对象。

It would look like something:

它看起来像一些东西:

//model definition (just an example)

var LatLng = function() {}
LatLng.prototype.getMapTypeId = function() {
   return this.mapTypeId;
}

//deserializing done like this
var result = JSMix(jsonString).withObject(LatLng.prototype, "latLngs").build();

//all items in the latLngs collection have the functions coming from the model
console.log(result.latLngs[5].getMapTypeId());