javascript - Issue using JSON.stringify to convert associative array -


the issue happens when associative array programmatically apposed via literal definition. using stringify on literal definition works.

trying understand, used test literal definition.

var test = {     voice : { state : 'ready' } }; console.log('stringify test: ' + json.stringify(test)); 

and output i'd expect:

stringify test: {"voice":{"state":"ready"}} 

this isn't happening when initialize programmatically. should mention variable private member of object i've created, has accessor/getter methods. within constructor, have:

var states = {};  this.getstates = function() {     return states; }  this.setstate = function(newstate, mediatype) {     states[mediatype] = newstate } 

now run same test.

customobj.setstate('{ state: 'ready' }', 'voice'); var test = customobj.getstates();  console.log('stringify test: ' + json.stringify(test)); 

and output not expect:

stringify test: [] 

lastly double check test variable has with:

for(var x in test) {     console.log('state in test: ' + x);     console.log('value of ' + x + ': ' + json.stringify(test[x]));  } 

and get:

state in test: voice value of voice: {"state":"ready"} 

ok, that's telling me contains i'm expecting, stringify() doesn't format it. now, i'm left confused what's going on.

i not sure how creating customobj following works:

var customobj = function () {     var states = {};      this.getstates = function()     {         return states;     }      this.setstate = function(newstate, mediatype)     {         states[mediatype] = newstate     } };  var customobj = new customobj(); customobj.setstate({ state: 'ready' }, 'voice');  var test = customobj.getstates(); console.log('stringify test: ' + json.stringify(test)); 

it outputs:

stringify test: {"voice":{"state":"ready"}} 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -