循环遍历 JSON 解析循环遍历每个字符。

32 浏览
0 Comments

循环遍历 JSON 解析循环遍历每个字符。

我正在尝试循环遍历一个从PHP获取到的JSON字符串,但我遇到的问题是,当我尝试循环遍历字符串时,它并不会循环遍历每个对象,而是循环遍历字符串中的每个字符。

我以为解决方法是解析它,但并没有成功。

var json = JSON.stringify(player.get(url));
console.log(json);
json = $.parseJSON(json);
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        console.log(key + " -> " + json[key]);
    }
}

我得到了一个完美的JSON结果,因为我在在线转换器中进行了测试 -

{

"id": "1",

"username": "Jessica",

"password": "password",

"age": "100",

"size": "100"

}

然而,当我遍历它时,控制台显示如下:

0 -> { index.html:29

1 -> " index.html:29

2 -> 0 index.html:29

3 -> " index.html:29

4 -> : index.html:29

5 -> " index.html:29

6 -> 1 index.html:29

7 -> " index.html:29

8 -> , index.html:29

9 -> " index.html:29

10 -> c index.html:29

11 -> h index.html:29

12 -> a index.html:29

13 -> r

为什么它不能正确地循环遍历json对象呢?

0
0 Comments

问题的原因是在代码中将一个字符串转换为JSON两次,但只解析了一次。这是不合理的,因为如果player.get(url);返回包含JSON的字符串,就不需要再将json字符串转换为JSON。

解决方法是将代码中的var json = JSON.stringify(player.get(url));更改为var json = player.get(url);。这样只需要解析一次数据,而不需要将字符串转换为JSON。

通过查看之前的帖子,发现了这个问题,并且得到了解决。非常感谢!

0