已验证JSON引发的SyntaxError:属性必须是字符串文字



我有一个经过验证的JSON,我正在把它拉到我的应用程序中,但一旦我选择了一个与JSON相关的项目,应用程序就会永远进入一个"加载";周期

我收到的错误是Error: Uncaught (in promise): SyntaxError: JSON Parse error: Property name must be a string literal

这是我验证过的JSON:

{
"lodges": [

{
"title": "Lakeside Lodge",
"url_title": "lakeside-lodge",                      
"lodges_short_name": "Lakeside",
"lodges_description": "<h5><strong>Coming Soon: Estimated Opening Fall 2021 </strong></h5><p>The Lakeside Lodge sits will rest in the center of this premier state park, <a href="/parks/lakeside">Lakeside State Park</a>.</p>",
"lodges_summary": "<p>Anticipated opening in Fall 2021, the new 85-room Lodge at Lakeside State Park!</p>",
"reservation_link": "null"
}
]
}

这是我用来获取并显示在数据中的代码:

showAmenities(item){
let list : any;
let res : any;
switch (item) {
case 'lodges':
this.data.getParkLodges(this.park).then(data => {
let res = JSON.parse(data);
let list = res.lodges;
this.openAmenityListPage(item,list);
}
}
}
openAmenityListPage(item,list){
let amenitiesModal = this.modalCtrl.create(ParkAmenitiesListPage, {title : item, listItems: list, park: this.parkDetails.title, parkShortName: this.parkShortName });
amenitiesModal.present();   
}

我可以获取数据并显示其他相同的JSON,但由于某种原因,这个JSON抛出了这个错误。

编辑:我正在使用其他在其值中包含HTML标记的API,这些API运行得非常好。

您的JSON字符串包含转义的双引号:<a href="/parks/lakeside">
逃跑"迷路了";只要JSON代码被Javascript解释为字符串。字符串中的转义引号变为普通引号:
console.log('a text with "quotes".') // --> logs 'a text with "quotes"'.

因此,在您的情况下,JSON.parse()看到的实际字符串(导致解析错误(如下:

'{ "lodges_description": "<a href="/parks/lakeside">" }, ...'

您需要对转义符进行转义,以便Javascript知道您要将实际的反斜杠字符传递给JSON.parse()函数:

console.log('a text with \"quotes\".') // --> logs 'a text with "quotes"'.

发现API与我正在使用的包含额外逗号的通道之间存在关系。:D

这个问题已经结束了。

最新更新