Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Ian Svoboda
Ian Svoboda
16,639 Points

Error returned on $.parseJSON()

I am attempting to parse a JSON object located on another page on my website. The page is a hosted ecommerce platform, so I don't have server side access or control over certain elements on page.

I have some code that i'm using that is returning a strange error. I've tested this snippet (with a different URL of course) on another site running the same platform and it does it fact work.

website: http://www.falcontechjax.com

$.get('no-risk-diagnostic-2.aspx', function(data) {
var prodImgDetail = $.parseJSON($(data).find("#imginfo").html());
console.log(prodImgDetail);
});

On that page, there is a div container with the id "imginfo, that contains a JSON object.

<div id="imginfo" style="display:none;">{gallery : [{thumbnail : '/images/products/thumb/pipe.jpg', display : '/images/products/display/pipe.jpg', detailed : '/images/products/detail/pipe.jpg', alt : '', title : '' },{thumbnail : '/images/products/thumb/logo_printres1.jpg', display : '/images/products/display/logo_printres1.jpg', detailed : '/images/products/detail/logo_printres1.jpg', alt : 'PC Computer Diagnostic &amp; Repair in Jacksonville FL', title : '' }],active : {thumbnail : '/images/products/thumb/pipe.jpg', display : '/images/products/display/pipe.jpg', detailed : '/images/products/detail/pipe.jpg', alt : '', title : '' }}</div>

The error I get when I run it is:

Uncaught SyntaxError: Unexpected token g jquery-1.7.2.min.js

Just to advise: there is a version of this setup which works on another site on the same platform as mine:

Site: www.allvintagegames.com

$.get( "nes-adventures-of-bayou-billy.aspx", function( data ) {
        var imgThumb, imgDisplay, imgDetailed, imgAlt, imgTitle;
        var mycrap = $.parseJSON($(data).find("#imginfo").html());   
        //img information
        $.each(mycrap.gallery, function(i, object) {
               //alert(object);
               imgThumb = object.thumbnail;
               imgDisplay = object.display;
               imgDetailed = object.detailed;
               imgAlt = object.alt;
               imgTitle = object.title;
        });
        //product information
        var prodinf = $.parseJSON($(data).find("#iteminfo").html());
               var infoLowprice = prodinf.lowprice;
               var infoId = prodinf.id;
               var infoName = prodinf.name;
               var infoCaption = prodinf.caption;
               var infoPrice = prodinf.price;
               var infoSaleprice = prodinf.saleprice;
               var infoCode = prodinf.code;
               var infoOrderable = prodinf.orderable;                
               $("body").append("<img src='"+imgThumb+"' />");
               $("body").append("<img src='"+imgDisplay+"' />");
               $("body").append("<img src='"+imgDetailed+"' />");
               $("body").append("<br />");
               $("body").append(infoLowprice + "<br/>");
               $("body").append(infoId + "<br/>");
               $("body").append(infoName + "<br/>");
               $("body").append(infoCaption + "<br/>");
               $("body").append(infoPrice + "<br/>");
               $("body").append(infoSaleprice + "<br/>");
               $("body").append(infoCode + "<br/>");
               $("body").append(infoOrderable + "<br/>");
});

This last example includes another object (#iteminfo contents) which is reference on the applicable page, just under the #imginfo div.

Any help figuring this out would be most appreciated!

4 Answers

Ethan Ferrari
Ethan Ferrari
3,017 Points

Hola. Parsing external JSON objects has given me difficulty as well. Try instantiating your variable outside the ajax call, then use a callback function to get the data when the call has finished.

var prodImgDetail; // create a variable to hold your result
var $pid = $.ajax({  // create a variable to hold your retrieved data
    url: 'no-risk-diagnostic-2.aspx',
    type: 'get',
    dataType: 'json'
});
var $imageInfo = $pid.find('#imginfo');  // create a variable to hold your json object

$pid.done(function () {  // callback
    productImgDetail = $.parseJSON($imginfo.responseText);  // set result variable to parsed json object
//do stuff
});

I've used something very similar to great effect, however it was without the .find() method on the data, so I'm not sure how that plays into the picture. Hope this helps.

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

HI Ian Svoboda

I just tried using the .load() method to solve this problem. Kind of an unusual use case, but it seems to work:

// create temporary jQuery object to hold retrieved data
var $data = $("<div></div>");
// the .load() method lets you access the contents of an element
// by adding an ID selector after the URL. In this example
// only the contents of #imgInfo will load into our temporary holder
$data.load('no-risk-diagnostic-2.aspx #imgInfo', function() {
      // extract text from temp holder and parse
      var parsedData = $.parseJSON($data.text());
      // empty temp holder, you don't need it anymore
      // because the data is now held in parsedData
      $data = null;
});

I hope that works for you.

Ian Svoboda
Ian Svoboda
16,639 Points

I appreciate the help. Can one of you perhaps explain why the example code (provided towards the end of the post) does in fact work on a different store (allvintagegames.com) on the same platform as mine?

See the example code and you can test it by running it in the console on his webpage.

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Ian Svoboda

The error you are getting is a JSON parsing error. You should output the HTML you're extracting from the returned data to make sure you are ONLY getting JSON data:

$.get('no-risk-diagnostic-2.aspx', function(data) {
  console.log($(data).find("#imginfo").html());
});

The error Uncaught SyntaxError: Unexpected token g jquery-1.7.2.min.js is telling me that you've got other text (not just JSON) that you are trying to parse.