将 JavaScript 对象序列化为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8164802/
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-24 04:56:17  来源:igfitidea点击:

Serialize JavaScript object into JSON string

javascriptjsonconstructor

提问by Kalamarico

I have this JavaScript prototype:

我有这个 JavaScript 原型:

Utils.MyClass1 = function(id, member) {
this.id = id;
this.member = member;
}

and I create a new object:

我创建了一个新对象:

var myobject = new MyClass1("5678999", "text");

If I do:

如果我做:

console.log(JSON.stringify(myobject));

the result is:

结果是:

{"id":"5678999", "member":"text"}

but I need for the type of the objects to be included in the JSON string, like this:

但我需要将对象的类型包含在 JSON 字符串中,如下所示:

"MyClass1": { "id":"5678999", "member":"text"} 

Is there a fast way to do this using a framework or something? Or do I need to implement a toJson()method in the class and do it manually?

有没有使用框架或其他东西的快速方法来做到这一点?还是我需要toJson()在类中实现一个方法并手动执行?

回答by Jakub Konecki

var myobject = new MyClass1("5678999", "text");
var dto = { MyClass1: myobject };
console.log(JSON.stringify(dto));

EDIT:

编辑:

JSON.stringifywill stringify all'properties' of your class. If you want to persist only some of them, you can specify them individually like this:

JSON.stringify将字符串化您班级的所有“属性”。如果您只想保留其中的一些,您可以像这样单独指定它们:

var dto = { MyClass1: {
    property1: myobject.property1,
    property2: myobject.property2
}};

回答by MSS

It's just JSON? You can stringify()JSON:

这只是JSON?你可以stringify()JSON:

var obj = {
    cons: [[String, 'some', 'somemore']],
    func: function(param, param2){
        param2.some = 'bla';
    }
};

var text = JSON.stringify(obj);

And parse back to JSON again with parse():

并再次解析回 JSON parse()

var myVar = JSON.parse(text);

If you have functions in the object, use this to serialize:

如果对象中有函数,请使用它来序列化:

function objToString(obj, ndeep) {
  switch(typeof obj){
    case "string": return '"'+obj+'"';
    case "function": return obj.name || obj.toString();
    case "object":
      var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
      return ('{['[+isArray] + Object.keys(obj).map(function(key){
           return '\n\t' + indent +(isArray?'': key + ': ' )+ objToString(obj[key], (ndeep||1)+1);
         }).join(',') + '\n' + indent + '}]'[+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g,'');
    default: return obj.toString();
  }
}

Examples:

例子:

Serialize:

连载:

var text = objToString(obj); //To Serialize Object

Result:

结果:

"{cons:[[String,"some","somemore"]],func:function(param,param2){param2.some='bla';}}"

Deserialize:

反序列化:

Var myObj = eval('('+text+')');//To UnSerialize 

Result:

结果:

Object {cons: Array[1], func: function, spoof: function}

回答by dips

This might be useful. http://nanodeath.github.com/HydrateJS/https://github.com/nanodeath/HydrateJS

这可能有用。 http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS

Use hydrate.stringifyto serialize the object and hydrate.parseto deserialize.

使用hydrate.stringify序列化对象和hydrate.parse反序列化。

回答by Willem Mulder

Well, the type of an element is not standardly serialized, so you should add it manually. For example

嗯,元素的类型不是标准序列化的,所以你应该手动添加它。例如

var myobject = new MyClass1("5678999", "text");
var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject };
console.log(JSON.stringify(toJSONobject));

Good luck!

祝你好运!

edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructorfor more information on the constructor property for Objects.

编辑:将 typeof 更改为正确的 .constructor。有关对象的构造函数属性的更多信息,请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor

回答by Elias Hossain

Below is another way by which we can JSON data with JSON.stringify() function

下面是我们可以使用 JSON.stringify() 函数获取 JSON 数据的另一种方式

var Utils = {};
Utils.MyClass1 = function (id, member) {
    this.id = id;
    this.member = member;
}
var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") };
alert(JSON.stringify(myobject));

回答by Geuis

You can use a named function on the constructor.

您可以在构造函数上使用命名函数。

MyClass1 = function foo(id, member) {
    this.id = id;
    this.member = member;
}

var myobject = new MyClass1("5678999", "text");

console.log( myobject.constructor );

//function foo(id, member) {
//    this.id = id;
//    this.member = member;
//}

You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

您可以使用正则表达式从 myobject.constructor 中解析出 'foo' 并使用它来获取名称。

回答by Роман Зыков

    function ArrayToObject( arr ) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i){
        var name = arr[i].name;
        var value = arr[i].value;
        obj[name] = arr[i].value;
    }
    return obj;
    }

      var form_data = $('#my_form').serializeArray();
            form_data = ArrayToObject( form_data );
            form_data.action = event.target.id;
            form_data.target = event.target.dataset.event;
            console.log( form_data );
            $.post("/api/v1/control/", form_data, function( response ){
                console.log(response);
            }).done(function( response ) {
                $('#message_box').html('SUCCESS');
            })
            .fail(function(  ) { $('#message_box').html('FAIL'); })
            .always(function(  ) { /*$('#message_box').html('SUCCESS');*/ });

回答by urza9814

I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues. So I put together the following functions which I am using instead:

我在使用带有“关联数组”类型对象的上述解决方案时遇到了一些问题。这些解决方案似乎保留了这些值,但它们并没有保留这些值所关联的对象的实际名称,这可能会导致一些问题。所以我把我正在使用的以下函数放在一起:

function flattenAssocArr(object) {
  if(typeof object == "object") {
    var keys = [];
    keys[0] = "ASSOCARR";
    keys.push(...Object.keys(object));
    var outArr = [];
    outArr[0] = keys;
    for(var i = 1; i < keys.length; i++) {
        outArr[i] = flattenAssocArr(object[keys[i]])
    }
    return outArr;
  } else {
    return object;
  }
}

function expandAssocArr(object) {
    if(typeof object !== "object")
        return object;
    var keys = object[0];
    var newObj = new Object();
    if(keys[0] === "ASSOCARR") {
        for(var i = 1; i < keys.length; i++) {
            newObj[keys[i]] = expandAssocArr(object[i])
        }
    }
    return newObj;
}

Note that these can't be used with any arbitrary object -- basically it creates a new array, stores the keys as element 0, with the data following it. So if you try to load an array that isn't created with these functions having element 0 as a key list, the results might be...interesting :)

请注意,这些不能与任何任意对象一起使用 - 基本上它会创建一个新数组,将键存储为元素 0,其后是数据。因此,如果您尝试加载一个不是使用这些函数创建的数组,该函数将元素 0 作为键列表,结果可能是……有趣的 :)

I'm using it like this:

我是这样使用它的:

var objAsString = JSON.stringify(flattenAssocArr(globalDataset));
var strAsObject = expandAssocArr(JSON.parse(objAsString));