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

查看:169
本文介绍了如何序列化&反序列化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对象的[de]序列化的最新技术(当然是在javascript中)。

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

谢谢,
斯图尔特

Thanks, Stewart

推荐答案

一般来说,没有办法(在浏览器中)串行化附加功能的对象,因为每个函数都有一个参考它的外部范围。如果函数引用了这些变量中的任何一个,那么在反序列化它们时它们将不再存在。

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.

我想使用内置的(或json2.js) ) JSON.stringify JSON.parse 具有替代品的函数 reviver 参数。以下是它如何工作的部分示例:

What I would to 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天全站免登陆