简体   繁体   English

将字符串转换为数组JavaScript

[英]Convert string to array JavaScript

I have urlencoded JSON data: 我已经使用urlencoded JSON数据:

%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. 我正在制作一个页面,该页面将使用出现此问题的Google Charts显示图表。 All help is welcome! 欢迎所有帮助!

Use JSON.parse 使用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 使用eval也可以,但是如果您从不受信任的来源(例如URL参数)获取该值,那么您可能会受到脚本注入的欺骗,该参数可能被欺骗进行钓鱼

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM