Search code examples
apimeteorjsonp

How to properly parse JSONP callback function in Meteor?


Does someone know how to parse JSONP callback in Meteor server methods?

I do

let response = HTTP.call('GET', AVIASALES_API_ENDPOINTS.getLocationFromIP, {
  params: {
    locale: 'en',
    callback: 'useriata',
    ip: clientIP
  }
});

in response.content I’ve got

useriata({"iata":"MSQ","name":"Minsk","country_name":"Belarus"})

How to properly parse it?


Solution

  • It could help to know what you really try to accomplish? But here is a working example meteor actually doesn't do anything unusual with the requests.

    Meteor.startup(function () {
        var result = HTTP.call("GET", "https://api.github.com/legacy/repos/search/meteor", {
            params: {},
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"
            }
        });
        console.log(result.data); // it's js object you can do result.data.repositories[0].name
        console.log(JSON.stringify(result.data)); // json string
        console.log(JSON.parse(JSON.stringify(result.data))) // if for some reason you need to parse it this way will work, but seems unnecessary 
    });
    

    Update: The string you got back from the response wasn't valid JSON so you couldn't parse it used some regex to remove the invalid strings here is working example: http://meteorpad.com/pad/JCy5WkFsrtciG9PR5/Copy%20of%20Leaderboard