0

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!

11
  • 3
    eval is your friend Commented Mar 28, 2014 at 21:13
  • 1
    or JSON.parse -> jsfiddle.net/adeneo/9bzVg Commented Mar 28, 2014 at 21:14
  • It's fine. Thank you so much! Commented Mar 28, 2014 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. Commented Mar 28, 2014 at 21:19
  • @JuanMendes - "eval is your friend" is more of a joke really, as opposed to the usual "eval is evil". Commented Mar 28, 2014 at 21:21

1 Answer 1

3

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

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

1 Comment

Good. Thank you for submitting an answer instead of a comment. That way I can accept it

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.