Converting an object to a string

后端 未结 30 1913
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log(\'Item: \' + o)

Output:

30条回答
  •  悲&欢浪女
    2020-11-22 04:17

    If you are using the Dojo javascript framework then there is already a build in function to do this: dojo.toJson() which would be used like so.

    var obj = {
      name: 'myObj'
    };
    dojo.toJson(obj);
    

    which will return a string. If you want to convert the object to json data then add a second parameter of true.

    dojo.toJson(obj, true);
    

    http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson

提交回复
热议问题