How to parse JSONP data returned from remote server

26,096

Solution 1

You don't have to parse the data. It is already a valid JavaScript object. For instance, to print the description property for the first object inside someFunction

function someFunction(result) {
    alert(result[0].description); // alerts "Sample Description"
}

Solution 2

Write a function with the correct name and the correct arguments. The JS engine will do the parsing for you.

function someFunction(data) {
    // Now data is an Array, containing a single
    // Object with 8 properties (title, link, etc)
}
Share:
26,096
user2487501
Author by

user2487501

Professional PHP developer. I'm here to learn new things from people more established than me, and to help those who are not.

Updated on July 09, 2022

Comments

  • user2487501
    user2487501 almost 2 years

    I am trying to grab some data via JSONP. Using Firebug, I am able to see the data properly being returned, but I am having a hard time thinking how I have to parse it. The data return is really a nested array correct? someFunction is the name of the callback function. This is how the data looks:

    someFunction([  
    {  
           "title":"Sample Title",  
           "link":"http://example.com",  
           "description":"Sample Description",  
           "publisher":"Sample Publisher",  
           "creator":"Sample Author",  
           "date":"Thu, 19 Aug 2010 12:41:29 GMT",  
           "num_pages":10,  
           "num_results":"10"  
    },  
    ]);
    

    Just a little confused about how to properly parse and output.

  • Ken J
    Ken J almost 10 years
    Just to be clear: For this example there is 1 object with 8 properties, but other servers may return JSON with multiple objects. Using console.log(data) is useful to get a list of objects returned.