Kelly Norton Kelly Norton - 2 years ago 121
JSON Question

Searching for item in JSON returned from API query with Node

I'm at the very beginning of my Node journey and writing my first tiny app. I want to query a stock code from and return the current stock price. I've got the query and response working fine, but I can't work out how to sort through the returned data to extract just the current price. Here is the code I am running:

var http = require('http');
var options = {
host: '',
port: 80,
path: '/MODApis/Api/v2/Quote/jsonp?symbol=AAPL&callback=myFunction',
method: 'GET'

http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
res.on('data', function (chunk) {

This is the data I receive back from the server:

myFunction({"Status":"SUCCESS","Name":"Apple Inc","Symbol":"AAPL","LastPrice":100.33,"Change":-0.0799999999999983,"ChangePercent":-0.0796733393088321,"Timestamp":"Fri May 27 15:59:00 UTC-04:00 2016","MSDate":42517.6659722222,"MarketCap":549550050250,"Volume":3169443,"ChangeYTD":105.26,"ChangePercentYTD":-4.68364050921528,"High":100.47,"Low":99.26,"Open":99.49})

How do I search through this to extract the 100.33 from the "LastPrice":100.33 key value pair? I thought of using the .filters method, but I don't believe what is being returned is a properly formatted array?

Thank you!

Answer Source

Request JSON instead of jsonp. That way you can use JSON.parse. jsonp is designed for browsers trying to work around CORS policies. Since you are running a server, you don't need to worry about such things.

URL (notice /json? instead of /jsonp?):


const json = JSON.parse(chunk);


If that API sends chunked JSON, you may need to accumulate the chunks before parsing. Something like:

  let data = '';

  res.on('data', function (chunk) {
    data += chunk;  

  res.on('end', function () {
    const json = JSON.parse(data);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download