1

I am trying to get scores from an API in node.js and I get a response that seems like a function. I am not exactly sure how to get the JSON data out of this function.

var req = http.request(options, function(res){
    res.setEncoding('utf8');
    res.on('data', function(data){
        console.log(data);
    });
});

The response is ...

shsMSNBCTicker.loadGamesData({
"sport": "NBA", 
"period": "20140426", 
"games": [""]
});

Within "games" is a bunch of data but that is unimportant and would take up way too much space. For this example, let's just say I am trying to get "sport"; which would return "NBA."

Collin McGuire
  • 714
  • 3
  • 8
  • 14

1 Answers1

2

The response you're getting is JSONP. Usually an API will offer both JSON and JSONP configurable with a parameter. However, since your asking here I'm going to assume you have no control over the request (perhaps a polite message to the API author might help).

You could either provide the namespace used in the response and eval the response. But since this is Node and not a browser the idea is silly at best. I would recommend, instead, to manually manipulate the response into JSON:

JSON.parse(response.replace(/^[^\(]*\(/, '').replace(/\);$/, ''));
Sukima
  • 9,965
  • 3
  • 46
  • 60
  • I was able to just remove the "JSONP" and used "JSON" in the url for the request. It gave me a JSON which is what I was looking for. Also, within the games array in the response from the API is XML. Off the top of your head do you know any good tutorials to extract the data from an array of XML tags? – Collin McGuire Apr 27 '14 at 02:59
  • 1
    @CollinMcGuire NPM probably has many XML parsers. Google found this: https://github.com/Leonidas-from-XIV/node-xml2js – Sukima Apr 27 '14 at 03:05