I have the 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 that the variable inputString is assigned everything between the curly braces. I'm a js novice but I think that is a convention to indicate some sort of object. That kind of string assignment looks strange to me, but it works as demonstrated above.
My issue is when I try to assign the variable inputString to string literal, as 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 someone with a deep understanding of javascript can explain this to me.
Thank you
1 Answer 1
That is because it is not object it is just a string.
var inputString2 ='{"Key1":"Planes","Key2":"Trains","Key3":"Cars","Key4":"Caoch","Key5":"Cycles","Key6":"Bikes"}'
You need to remove quotes around your json. It should be like this.
var inputString2 ={"Key1":"Planes","Key2":"Trains","Key3":"Cars","Key4":"Caoch","Key5":"Cycles","Key6":"Bikes"}
If you get it as string. Use JSON.parse
var convertedJson = JSON.parse(inputString2);
var value = convertedJson ["Key3"];
alert(value);
evalon that string.... j/k (don't do that) look into json.js json.org/js.htmlobject literal, the second one is just astring literal, most probably a string dump of a JSON object