RobertFrenette
RobertFrenette

Reputation: 627

Parse JSON returned from NODE.js

I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.

The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.

Here is the code:

index.html (snippet)

function getData() {
    $.ajax({
        url:       'http://127.0.0.1:3000',
        dataType:  'json',
        success:   function(data) {
            $("#results").html(data);
            alert(data.engineURL);  // alerts: undefined
        }
    }); 
}

server.js

function run(callBack) {
    var spawn = require('child_process').spawn,
    child = spawn('python',['test.py']);
    var resp = '';

    child.stdout.on('data', function(data) {
        resp = data.toString();
    });

    child.on('close', function() {
        callBack(resp);
    });
}

http.createServer(function(request, response) {
    run(function(data) {
        response.writeHead(200, {
            'Content-Type':
            'application/json',
            'Access-Control-Allow-Origin' : '*' });
        response.write(JSON.stringify(data));
        response.end();
    });
}).listen(PORT, HOST); 

test.py

import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})

After the AJAX call comes back, I execute the following:

$("#results").html(data);

and it prints the following on the web page:

{“engineURL": "http://www.google.com", "engineName": "Google"}

However, when I try and parse the JSON as follows:

alert(data.engineURL);

I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.

Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?

Thanks.

Upvotes: 1

Views: 721

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70189

I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.

Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:

data = $.parseJSON(data);

Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.


Also:

child.stdout.on('data', function(data) {
    resp = data.toString();
      // ^ should be +=
});

The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.

Upvotes: 2

Related Questions