Javascript string assignment to key-value string -


i have following code:

var inputstring ={"key1":"planes","key2":"trains","key3":"cars","key4":"caoch","key5":"cycles","key6":"bikes"}  var value = inputstring ["key3"]; alert(value); 

the above code works fine, notice variable inputstring assigned between curly braces. i'm js novice think convention indicate sort of object. kind of string assignment looks strange me, works demonstrated above.

my issue when try assign variable inputstring string literal, follows:

var inputstring2 ='{"key1":"planes","key2":"trains","key3":"cars","key4":"caoch","key5":"cycles","key6":"bikes"}'  var value = inputstring2 ["key3"]; alert(value); 

the above code returns undefined, why?

i'm sure deep understanding of javascript can explain me.

thank you

that because not object string.

var inputstring2 ='{"key1":"planes","key2":"trains","key3":"cars","key4":"caoch","key5":"cycles","key6":"bikes"}' 

you need remove quotes around json. should this.

 var inputstring2 ={"key1":"planes","key2":"trains","key3":"cars","key4":"caoch","key5":"cycles","key6":"bikes"} 

if string. use json.parse

 var convertedjson =  json.parse(inputstring2); var value = convertedjson ["key3"]; alert(value); 

see json.parse


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 -