使用TMDb API的JSON输入意外结束

时间:2019-03-27 22:32:54

标签: javascript json

我正在尝试解析The Movie DB返回的JSON数据。我收到一条错误消息,告诉我我收到以下错误消息:

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.movieReq.onreadystatechange (discover.js:34)
    at loadIMDBDetails (discover.js:38)
    at MainFunc (discover.js:68)
    at discover.js:5
I am accessing individual movie information using the following XMLHttpRequest:

movieReq.open('GET','https://api.themoviedb.org/3/movie/299537?api_key=',false);

我还有其他XMLHttpRequests可以返回JSON数据。这些请求正在使用API​​的发现功能。

这是产生问题的功能

function loadIMDBDetails(mO, i) {
    movieReq = new XMLHttpRequest();

    movieReq.onreadystatechange = function () {
        var parsedObj = JSON.parse(movieReq.responseText);
        mO.imdbId = parsedObj['imdb_id'];
    };
    movieReq.open('GET', 'https://api.themoviedb.org/3/movie/299537?api_key=34f8307d9addabf7924eab7f22cabb23', false);
    movieReq.send();
}

When using console.log to return the responseText, this is the result:

{“ adult”:false,“ backdrop_path”:“ / w2PMyoyLU22YvrGK3smVM9fW1jj.jpg”,“ belongs_to_collection”:null,“ budget”:152000000,“ genres”:[{“ id”:28,“ name”:“ Action“},{” id“:12,” name“:” Adventure“},{” id“:878,” name“:” Science Fiction“}],” homepage“:” https://www.marvel.com/movies/captain-marvel“, “ id”:299537,“ imdb_id”:“ tt4154664”,“ original_language”:“ en”,“ original_title”:“ Marvel船长”,“概述”:“故事讲述了Carol Danvers成为宇宙中最强大的人之一当地球陷入两个外星人种族之间的银河战争之中时的英雄人物。《惊奇队长》设定于1990年代,是漫威电影宇宙历史上从未见过的全新冒险。”,“受欢迎程度”: 419.096,“ poster_path”:“ / AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg”,“ production_companies”:[{“ id”:420,“ logo_path”:“ / hUzeosd33nzE5MCNsZxCGEKTXaQ.png”,“名称”:“ originStudios US“}],” production_countries“:[{” iso_3166_1“:” US“,” name“:”美利坚合众国“}],” release_date“:” 2019-03-06“,” revenue“:910298835, “运行时”:124,“口语”语言”:[{“ iso_639_1”:“ en”,“名称”:“英语”}]],“状态”:“已发布”,“标语”:“高级。进一步。更快。“,” title“:”惊奇队长“,”视频“:false,” vote_average“:7.3,” vote_count“:2885}

2 个答案:

答案 0 :(得分:1)

事实证明,我已经忘记为onreadystatechange事件添加检查了。我添加了以下检查,并在if语句中运行json解析,这解决了我的问题!

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

答案 1 :(得分:0)

如果我正确理解您回来时的问题 console.log(movieReq.responseText) 在行上方:

var parsedObj = JSON.parse(movieReq.responseText);

您获得正确的JSON,对吗?

如果是这样,则意味着您不需要使用功能JSON.parse(),就可以直接访问对象movieReq.responseText的任何元素,在这种情况下,您可以访问movieReq.responseText.imdb_id,而无需对其进行解析(因为它已经是一个JSON对象)。

如果要将字符串转换为JSON对象,只需使用JSON.parse(),有关更多信息,请检查:https://www.w3schools.com/js/js_json_parse.asp