0

i have a little problem, i am a beginner in programming. I want to work with the Erast API, a Formula 1 API. I want to get all the drivers who won single races, the request is the following: http://ergast.com/api/f1/current/results/1.json

Structure of the return values:

Problem is, that i dont know how to parse the JSON into a JS Array, I thought something like that:

var names = [];
    var index = 0;
    $.getJSON("http://ergast.com/api/f1/current/results/1.json", function(data, status) {
        $.each(data.MRData.RaceTable.Races, function(name, value) {
            //names.push(value.Results[0].Driver.givenName + " " + value.Results[0].Driver.familyName));
            obj = $.parseJSON(value);
            names.push(obj.Results[0].Driver.givenName);
            //console.log(value.Results[0].Driver.givenName+ " " + value.Results[0].Driver.familyName);
        });
    });

If anyone knows the answer, would appreciate hearing from you

4
  • 1
    use $.parseJSON on the whole JSON string and then iterate through the results. You're trying to access data.MRData before you've parsed the string. Commented May 16, 2017 at 18:22
  • 1
    @DanielBeck, that is wrong information: jQuery does the parsing. Commented May 16, 2017 at 18:23
  • And without seeing sample JSON, it's difficult to know if the extra parseJSON() call in the loop is necessary. Commented May 16, 2017 at 18:24
  • Ah, whoops, I missed that it was $.getJSON instead of $.get(). Thanks @trincot. In that case you may not need to use parseJSON inside the loop at all. Commented May 16, 2017 at 18:24

1 Answer 1

1

There is no need to parse JSON in the loop: jQuery has already decoded the JSON when it got the response in its implementation of $.getJSON.

So you can do this (also using map()):

$.getJSON("http://ergast.com/api/f1/current/results/1.json", function(data, status) {
    var names = data.MRData.RaceTable.Races.map(function(value) {
        return value.Results[0].Driver.givenName;
    });
    console.log(names);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.