0

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

3
  • Why are you trying to use Object methods with a string? Commented May 9, 2013 at 15:52
  • You need to use eval on that string.... j/k (don't do that) look into json.js json.org/js.html Commented May 9, 2013 at 15:54
  • this "some sort of object" is actually called an object literal, the second one is just a string literal, most probably a string dump of a JSON object Commented May 9, 2013 at 16:01

1 Answer 1

5

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);

See JSON.parse

Sign up to request clarification or add additional context in comments.

3 Comments

Hi PSL, is there a way to turn inputString2 from a string into an object, so it can work?
Use JSON.parse(inputString2)
Don't wrap the curly braces with quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.