SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist bradical1379's Avatar
    Join Date
    Feb 2007
    Posts
    443
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JSONP error: Cannot read property '0' of undefined

    I have some JSON data that I am trying to parse through Javascript and I keep receiving a Cannot read property '0' of undefined error.

    This is a short snippet of the data that comes in: "shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"1.5"}]

    As I loop through my JSON results, I use this code to grab the shippingInfo data:

    var shipping = parseFloat(items.shippingInfo[0].shippingServiceCost[0].__value__);

    However, it appears each time that I receive and error on the shippingServiceCost[0] array, saying its undefined.

    Any ideas?

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,869
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    I tested with the following code and had the alert displaying 1.5 as expected.

    Code:
    var items = '"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"1.5"}]}]';
    items = JSON.parse('{'+items+'}');
    alert(items.shippingInfo[0].shippingServiceCost[0].__value__);
    I had to add the extra }] to the end to close the data - I assume that you have further values following in the actual string and that those two characters are at the end.

    I am not really sure why you can't get your code to work - there isn't exactly all that much code required.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Evangelist bradical1379's Avatar
    Join Date
    Feb 2007
    Posts
    443
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am not sure if this makes any difference, but this is how I loop through the items:
    Code JavaScript:
    $.each(data.findItemsByKeywordsResponse[0].searchResult[0].item, function(i,items){
     
    	var shipping = parseFloat(items.shippingInfo[0].shippingServiceCost[0].__value__);
     
    });

    Using JQuery 1.7


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •