[英]How to properly use JSON.parse in this sample code (string to array)?
I'm trying to store an array in StriptProperties
converting it to a string and recovering this way: 我正在尝试在
StriptProperties
存储一个数组,将其转换为字符串并以这种方式恢复:
var personDataArr = ["Adam", "male", "programmer"];
function myFunction() {
var personDataStr = JSON.stringify(personDataArr);
ScriptProperties.setProperty('personData', personDataStr);
var personData = ScriptProperties.getProperty('personData');
personData = JSON.parse("[" + personData + "]");
Logger.log("personData[0] = " + personData[0]);
}
But when I log Logger.log("personData[0] = " + personData[0]);
但是当我记录
Logger.log("personData[0] = " + personData[0]);
I get personData[0] = Adam,male,programmer
instead of Adam
. 我得到
personData[0] = Adam,male,programmer
而不是Adam
。 Why? 为什么? How to get, instead, the first element of the array?
相反,如何获得数组的第一个元素?
You need to remove square brackets ( []
) from JSON.parse
function: 您需要从
JSON.parse
函数中删除方括号( []
):
personData = JSON.parse( personData );
This happens because you create multidimentional array ant it looks in final result as: 发生这种情况是因为你创建了多维数组,它在最终结果中看起来像:
[["Adam", "male", "programmer"]]
This is why 0
index of that array return Array
for you and not Adam
value 这就是为什么该数组的
0
索引为您返回Array
而不是Adam
值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.