简体   繁体   中英

Node.js and Express - Sending JSON object from SoundCloud API to the front-end makes it a string

I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.

var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
    tracks.on('data', function (chunk) {
        console.log(typeof(chunk)); // where I determine that I receive an object
        res.send(chunk);
    });
    //console.log(tracks.data);
}).on("error", function(e){
    console.log("Got error: "+e);
});

But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())

$('#search').click(function(e){
  e.preventDefault();  
  var q = $("#query").val();
  $.ajax({ 
        url: '/search',
        type: 'POST', 
        data: { 
          "query": q
        }, 
        success: function(data){
          alert(typeof(data));
          alert(data);
        }, 
        error: function(xhr, textStatus, err){
          alert(err);
        }
      })
  });    

I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)

JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.

var obj = JSON.parse(data);


Another example would be:

var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22 

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