简体   繁体   English

JSON.parse 不会解析数组?

[英]JSON.parse won't parse array?

Here's a code snippet that's been throwing me for a loop:这是一个让我陷入循环的代码片段:

var _tids = [];
console.log("type:", typeof user._imported_readTids, "value:", user._imported_readTids);
try {
    _tids = JSON.parse(user._imported_readTids);
} catch(e) {
    return nxt();
}

console.log("user:", user.uid, "type:", typeof _tids, "\narray:", _tids);

in the first console.log , the type of the field _imported_readTids is a string, which is expected (a string representation of an array, like "[1,2,3]" (no spaces between elements))在第一个console.log中,字段 _imported_readTids 的类型是一个字符串,这是预期的(数组的字符串表示,如"[1,2,3]" (元素之间没有空格))

When I call JSON.parse on that string, I'm expecting it to be turned into an array, but on the second console.log , the type is still a string, and the array representation looks the same.当我在该字符串上调用 JSON.parse 时,我期望它会变成一个数组,但在第二个console.log ,类型仍然是一个字符串,并且数组表示形式看起来相同。

Here's the output:这是 output:

// first console.log (truncated for brevity):
type: string value: "[4,5,6,7,8,...,234]"

// second: 
user: 1 type: string 
array: [4,5,6,7,8,...,234]

I've tried these same params and used in a console nodejs process, and it comes out as expected, typeof jsonArray will return 'object' .我已经尝试了这些相同的参数并在控制台 nodejs 进程中使用,它按预期出现, typeof jsonArray将返回'object'

This is in NodeJS, v0.12.5, OSX 10.11.1 (El capitan)这是在 NodeJS, v0.12.5, OSX 10.11.1 (El capitan)

The first time you console.log it says that the string value starts and end with a " . 第一次console.log时,它说字符串值以"开头和结尾。

The second time, it does not say that. 第二次没有说。

You have a string representation of a JSON text which itself consists of a string representation of a JSON text which is an array. 您具有一个JSON文本的字符串表示形式,该字符串本身包含一个JSON文本的字符串表示形式,该JSON字符串是一个数组。

After you parse it, you have a string representation of a JSON text which is an array. 解析之后,您将获得一个JSON文本的字符串表示形式,它是一个数组。

ie Your array is double stringified, so you need to parse it twice (or fix whatever is encoding it in the first place so it only does it once). 即,您的数组是字符串化的,因此您需要对其进行两次解析(或首先修复对其进行编码的任何内容,以便仅执行一次)。

If you make this change on the php side, it will be solved.如果在php这边做这个改动,就解决了。 example: $x=[a,b,x];示例:$x=[a,b,x]; $x2=array(); $x2=数组();

$x2[]=$x; $x2[]=$x;

echo json_encode($x2);回声 json_encode($x2);

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

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