JSON.stringify() and JavaScript Objects

懵懂的女人 提交于 2019-12-10 13:14:18

问题


I'm thinking maybe I missed something in JavaScript that I'm just picking up now.

I tried this code in Chrome console:

a = [];
a.name = "test";
JSON.stringify(a); 
// which returns value []
a = new Object();
a.name = "test";
JSON.stringify(a); 
// which returns value {"name":"test"}

What is the difference? I thought new Object() was a Microsoft JScript thing? What am I missing? Must have missed something in a spec somewhere. Thanks.


回答1:


a = new Object()

and

a = []

are not equivalent. But,

a = {}

and

a = new Object()

are.




回答2:


new Object() is equivalent to {} (except when it's not because of weird redefinition issues - but ignore that for now.) [] is equivalent to new Array(), to which you're then adding a .name property. JSON stringifies arrays in a special way that doesn't capture arbitrary property assignment to the array itself.




回答3:


For JSON data, Arrays are meant to have numeric indices, and objects have key/value pairs.

a = [];
a[ 0 ] = "test";

JSON.stringify(a); // returns value ["test"]



回答4:


Yes you are using [] to define your object which is actually an array, but depending on the language you are coming from could be confusing because it is not an associative array.

Default objects are all maps of key->data and are instantiated with curly brackets {}

If you did

a = {};
a.name = "test";
JSON.stringify(a); 

It should work.




回答5:


Setting the name property of an array does nothing to its serialized (JSON-stringified) form. It doesn't put an entry into the array. To do that, you need a.push('test').

Objects are standard parts of Javascript (see, for instance, the MDC docs). The normal way to create an object is with {}, but new Object() works too.

So...

var a = [];
a.push('test');
JSON.stringify(a); //"["test"]"

a = {};
a.name = 'test';
JSON.stringify(a); //"{"name":"test"}"


来源:https://stackoverflow.com/questions/6021167/json-stringify-and-javascript-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!