【问题标题】:JSON error, half of the variable are undefinedJSON错误,一半变量未定义
【发布时间】:2017-05-14 22:21:46
【问题描述】:

所以我的 JSON 有问题。它给我一个未定义的。 奇怪的是它识别出我的第一个变量。

这里有代码来说明清楚。

JSON

{"Comics":[
{"comic" : 
    {
    "src":"Pictures/Comics/dw.jpg",
    "descr":"Doctor Who has a nice tv show."
    }
},
{"comic" : 
    {
    "src":"Pictures/Comics/spi.jpg",
    "descr":"Spider man is a nice comic \
            The main spider-man comic \
            ended with Peter Parker's \
            death."
    }
},
{"comic" : 
    {
    "src":"Pictures/Comics/gg.jpg",
    "descr":"Power puff girls also has a \
            nice tv show .   \
            You should try watching it."
    }
},
{"comic" : 
    {
"src":"Pictures/Comics/v.jpg",
"descr":"V fo Vendeta is a nice  \
            graphical volume written by\
            Allan Moor who also wrote \
            Watchmen. Those books had a movie."
    }
}


 ]
}

这是我的 Javascript

var arrI = new Array(4);
var arrD = new Array(4);

var x = new XMLHttpRequest;
x.onload = function(){
    if(x.status == 200){
    var txt = JSON.parse(x.responseText);
for(var g = 0; g<txt.Comics.length; g++){
        arrI[g] = txt.Comics[g].comic.src;
        arrD[g] = txt.Comics[g].comic.descr;
        alert(arrD[g]);
    }
    }
}

x.open("GET",'Ajax/ImgCom.json', true);
x.send(null);

奇怪的是arrI[g] = txt.Comics[g].comic.src; 没问题。如果我提醒它,它会给我src。但desc 不是。它提醒我undefined。我不明白为什么,毕竟他们都有好路。

我试图用https://jsonlint.com 纠正自己。 它告诉我:

Error: Parse error on line 5:
....jpg",               "descr": 'Doctor Who has a ni

----------------------^

Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

然后我尝试将 desc 的 " 更改为 ',但没有成功。

最后,我也尝试了...=txt.Comics[g].comic[desc] 表示法,但它仍然给 e undefined。

我更正了自己,我没有发现任何错字。也许有。

感谢您的宝贵时间。

【问题讨论】:

  • 从你的 json 中删除 \
  • 您是如何生成 JSON 的?您应该在自己喜欢的环境中使用标准 JSON 编码函数。永远不要尝试自己生成 JSON。

标签: javascript arrays json ajax


【解决方案1】:

您不能像在 JSON 中那样将字符串值拆分为多行。

{
"src":"Pictures/Comics/spi.jpg",
"descr":"Spider man is a nice comic \
        The main spider-man comic \
        ended with Peter Parker's \
        death."
}

需要改成这个……

{
"src": "Pictures/Comics/spi.jpg",
"descr": "Spider man is a nice comic The main spider-man comic ended with Peter Parker's death."
}

您还需要更改一些其他条目。 看这里 Multiline strings in JSON

【讨论】:

  • 谢谢,它在一行中工作得很好。另外,根据我从您的链接中了解到的内容,有一种方法可以制作多行字符串。现在没关系,但我本来想这样做的,我怎么能这样做?
  • JSON 不支持多行字符串值。如果您希望该值在多行上呈现,您可以将换行符 '\n' 编码到字符串值中。如果您希望 JSON 文档中的值跨多行显示以提高可读性,您可以将值类型更改为 Strings 的 Array,然后将它们加入您的代码中。
猜你喜欢
  • 2017-07-30
  • 2011-11-03
  • 1970-01-01
  • 2015-01-25
  • 2018-05-03
  • 2014-04-25
  • 2021-04-10
  • 2011-12-21
  • 2023-03-24
相关资源
最近更新 更多