Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have urlencoded JSON data:

%5B%5B"Task"%2C"Hours%20per%20Day"%5D%2C%5B"Work"%2C11%5D%2C%5B"Eat"%2C2%5D%2C%5B"Commute"%2C2%5D%2C%5B"Watch%20TV"%2C2%5D%2C%5B"Sleep"%2C7%5D%5D 

I have already decoded it to:

"[["Task","Hours per Day"],["Work",11],["Eat",2],["Commute",2],["Watch TV",0.5],["Sleep",7]]"

As you can see, this is a string, not an array, and I am trying to convert it to an array.

Sidenote:

I am making a page which will display charts using Google Charts that is having this problem. All help is welcome!

share|improve this question
3  
eval is your friend –  adeneo Mar 28 at 21:13
1  
or JSON.parse -> jsfiddle.net/adeneo/9bzVg –  adeneo Mar 28 at 21:14
    
It's fine. Thank you so much! –  Vulpus Mar 28 at 21:15
    
@adeneo eval is actually your enemy, use it wisely or never at all. This case is not a wise case to use it since the input is likely from a URL, which could be spoofed for phishing and you'd be subject to script injection. –  Juan Mendes Mar 28 at 21:19
    
@JuanMendes - "eval is your friend" is more of a joke really, as opposed to the usual "eval is evil". –  adeneo Mar 28 at 21:21

1 Answer 1

up vote 3 down vote accepted

Use JSON.parse

var jsArray = JSON.parse('[["Task","Hours per Day"],["Work",11],["Eat",2],["Commute",2],["Watch TV",0.5],["Sleep",7]]');
console.log(jsArray[0][0]) // "Task"
console.log(jsArray[0][1]) // "Hours per Day"

Using eval would also work but would expose you to script injection if you are getting that value from an untrusted source, like the URL parameters, which can be spoofed for fishing

share|improve this answer
    
Good. Thank you for submitting an answer instead of a comment. That way I can accept it –  Vulpus Mar 28 at 21:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.