javascript - JSON stringify values of array -


i'm trying stringify object don't know why not working expected:

function request(url) {   this.url = url;   this.head = []; }  var r = new request("http://test.com"); r.head["cookie"] = "version=1; skin=new"; r.head["agent"] = "browser 1.0"; document.write(json.stringify(r)); 

i hope object can stringified as:

{"url":"http://test.com","head":["cookie":"version=1; skin=new", "agent":"browser 1.0"]} 

but get:

{"url":"http://test.com","head":[]} 

how fix it?

you want hear property of r associative array think (like in php). don't exist in javascript. array's have values indexed number.

since r.head object (array object in js) can add properties r.head["whatever property name"]="value" these properties don't seem serialized json when use json.stringify because r.head defined array , it'll serialize numbered index values.

to fix can define r.head object json.stringify serialize properties.

function request(url) {   this.url = url;   this.head = {}; }  var r = new request("http://test.com"); r.head["cookie"] = "version=1; skin=new"; r.head["agent"] = "browser 1.0"; document.write(json.stringify(r)); 

if run following code in cosole (press f12 in browser) you'd see arrays not serialized in same way objects are:

var b = []; b.something=22 console.log(b.something); console.log(json.stringify(b));//=[] console.log(b.hasownproperty("something"))//=true   b = {}; b.something=22 console.log(b.something); console.log(json.stringify(b));//={"something":22} console.log(b.hasownproperty("something"))//=true 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -