1
var vString = "{ "var1":"varA", "var2":"varB", "var3":"varC" }";

var literalArray = vString;

console.log(literalArray["var1"]); // = varA

How can string be converted to a literal array?

1
  • That string is syntactically incorrect, and if it weren't it would be the JSON representation of an object but not an array. Commented May 3, 2016 at 13:13

2 Answers 2

2

Modify your code as given below:

var vString = '{ "var1":"varA", "var2":"varB", "var3":"varC" }';

var literalArray = vString;

console.log(JSON.parse(literalArray)["var1"]); 
Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible without JSON?
@CPLUSPLUS no. And it's not an array.
@CPLUSPLUS you may need to write your own parsing function for that. I see no harm in using JSON.parse as it's in-built in javascript.
If JSON.parse isn't available, eval will work, but is considered to be a very bad practice when not necessary.
1

This will work for you...

var string = '{"var1":"varA", "var2":"varB", "var3":"varC" }';
var objectArray = (new Function("return " + string+ ";")());
console.log(objectArray.var1);

2 Comments

Any Cons using this method?
@CPLUSPLUS, i don't think so,.. this is working for this simple string = "0,1,2"; also and it will split the string from comma's , only...

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.