BuddyJoe
BuddyJoe

Reputation: 71101

JSON.stringify() and JavaScript Objects

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.

Upvotes: 6

Views: 18715

Answers (5)

Anurag
Anurag

Reputation: 141869

a = new Object()

and

a = []

are not equivalent. But,

a = {}

and

a = new Object()

are.

Upvotes: 20

lonesomeday
lonesomeday

Reputation: 237845

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"}"

Upvotes: 1

Dan Davies Brackett
Dan Davies Brackett

Reputation: 10071

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.

Upvotes: 3

Quintin Robinson
Quintin Robinson

Reputation: 82335

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.

Upvotes: 1

user113716
user113716

Reputation: 322492

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"]

Upvotes: 1

Related Questions