如何序列化 &反序列化 JavaScript 对象? [英] How to serialize & deserialize JavaScript objects?

查看:40
本文介绍了如何序列化 &反序列化 JavaScript 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

注意这些对象包含函数,所以我不能将它们存储为JSON,所以我不能使用json2.js.

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

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

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

推荐答案

一般来说,(在浏览器中)没有办法序列化附加有函数的对象:每个函数都有对其外部作用域的引用,该作用域获胜'在反序列化时不存在,因此对该范围的序列化引用将无效.

In general, there's no way (in a browser) to serialize objects with functions attached to them: Every function has a reference to its outer scope, that scope won't exist when you deserialize it, so serialized references to that scope will be invalid.

我要做的是使用内置的(或 json2.js)JSON.stringifyJSON.parse 函数和 replacer> 和 reviver 参数.这是它如何工作的部分示例:

What I would do is use the built-in (or json2.js) JSON.stringify and JSON.parse functions with the replacer and reviver parameters. Here's a partial example of how it would work:

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

您可以在自定义类型中使用任何您想要的序列化格式.LatLng(纬度,经度)"格式只是一种方法.您甚至可以返回一个可以原生序列化为 JSON 的 JavaScript 对象.

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.

这篇关于如何序列化 &反序列化 JavaScript 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆