简体   繁体   中英

Issues With JSON.parse

I'm trying to create a search engine using the Giphy.API, but once I get to the third step and JSON.parse it gives me Unexpected token character at Json[0]. I think it is trying parse what I input and not the api data. Any help is appreciated.

/* 1. Grab the input*/

document.querySelector(".js-go").addEventListener('click',function(){
    var input = document.querySelector("input").value;
    pushToDOM(input);
    });
document.querySelector(".js-userinput").addEventListener('keyup',function(e){
    var input = document.querySelector("input").value;
    if(e.which=== 13) {
    pushToDOM(input);
        }
    });

/ 2. Do the API Data /

function pushToDOM(input){
    var search =  input ;
    console.log(search);
    var api= "http://api.giphy.com/v1/gifs/search?"
    var apikey= "&api_key=dc6zaTOxFJmzC"
    var query = "&q="+ search
    var url = api+apikey+query
    console.log(url);

// AJAX Request

    var GiphyAJAXCall = new XMLHttpRequest();
    GiphyAJAXCall.open( 'GET', url );
    GiphyAJAXCall.send();
    GiphyAJAXCall.addEventListener('load',function(e){

    var data = e.target.response;
    pushToDOM(data);
})};

/ 3. Show the gifs /

    function pushToDOM(input){

        var response = JSON.parse(input)
        //console.log(response)}
        var imgURLs = response.data;
        var container = document.querySelector(".js-container")
        container.innerHTML = data};
        imgURLs.forEach(function(image){

        var src = image.images.fixed_height.url;
        console.log(src)

        container.innerHTML +=  "<img src=\"" + src + "\" class= \"container-image\">";
        })}

The response from the giphy api in plain text comes back with a bunch of white space and line breaks either side of the JSON. You'll need to remove the initial whitespace and linebreaks, and then use .trim() to clear out this whitespace from the end of response before you can parse it. try something like:

var data = e.target.response.replace(/^\s+\{/, '{').trim();
pushToDOM(data);

Regex explained:

  • ^ denotes beginning of string
  • \\s denotes any whitespace character [\\r\\n\\t\\f\\v ]
  • + qualifier matches between one and unlimited times
  • \\{ denotes the literal character {

Replace the match with just the literal character { because we've captured it in our regex, then use javascript native .trim() method to strip trailing whitespace

If it makes you feel better, the problem was on the API side, not in your code :)

JSFIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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