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!

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top