-1

I want to get a list of repositories from my GitHub account and the URL that I am using is https://api.github.com/users/rakeshdas1/repos. I want to parse it using jQuery and output into a HTML page. The code that I am using to achieve this is:

$(document).ready(function(){
    var json = "https://api.github.com/users/rakeshdas1/repos";
    $.each(JSON.parse(json), function(idx, obj) {
        $("#repos").append("<p>"+obj.name+"</p>");
    });
});

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The first character in the JSON file is '[' and I don't know why jQuery can't parse it

DanielST
  • 13,783
  • 7
  • 42
  • 65
rakeshdas
  • 2,363
  • 5
  • 20
  • 28
  • 1
    There is no AJAX request being made here? `json` is a string containing the github repo URL, hence why calling `JSON.parse()` on it is erroring... – Rory McCrossan Apr 09 '15 at 18:56
  • Looks like you're attempting to parse the string `"https://api.github.com/users/rakeshdas1/repos"`. You need to make an actual GET request – em_ Apr 09 '15 at 18:59

1 Answers1

2

As Rory said in the comments, no AJAX request is being made. You are trying to parse the string "https://api.github.com/users/rakeshdas1/repos" as JSON.

What you may be looking for is a call to $.get to actually download the result of that API call, then parse it inside the function.

The following code fails for me due to network restrictions, but it should give you the right idea. It might even work for you.

$(document).ready(function () {
    var api = "https://api.github.com/users/rakeshdas1/repos";
    $.get(api, function (data) {
        $.each(data, function (idx, obj) {
            $("#repos").append("<p>" + obj.name + "</p>");
        });
    });
});
Scott
  • 5,338
  • 5
  • 45
  • 70
  • What do you mean by network restrictions? Your code produced the same error for me. – rakeshdas Apr 09 '15 at 19:44
  • If you `console.log(data)` inside the `$.get`, do you get an object, or a string? My code assumes jQuery automatically parses the JSON to a proper object, but if it's a string, replace `$.each(data` with `$.each(JSON.parse(data)`. – Scott Apr 09 '15 at 19:49
  • Thanks man, but I think I got it, I just called `$.ajax` with specific parameters, as shown [here](http://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript) and I got it work great! – rakeshdas Apr 09 '15 at 20:16