Tijmen Tijmen - 1 year ago 170
Javascript Question

JQuery GET with JSON response. Select specific objects

I'm working on a simple web app. This will have the client enter a license plate, then connect to a Socrata-based OpenData API which contains the records of all registered cars in my country.

Using the license plate, it must find the correct car, and display specific information. The kind of information displayed will differ, as I intend to use this app on several different web pages, but as a starting point I'd like to display the car's brand and model. These are listed in the array as

"merk" : "KIA"
"handelsbenaming" : "PICANTO"

Where 'Merk' is the brand/manufacturer and 'handelsbenaming' is the model.

I am not very experienced with javascript, and completely new to JQuery, but I managed to come up with this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
var kenteken = "1KBB00";

$.get("https://opendata.rdw.nl/resource/m9d7-ebf2.json",{kenteken: kenteken},function(data, status){
alert("Data: " + data + " Status: " + status);});



As you can see, the JQuery is fired by pushing the button. I'll make an input field to get the license plate number later on, but in for testing purposes I simply defined the variable "kenteken" to be a real license plate. Also for testing purposes I would like to return the response in an alert box.

On testing, the console in Firefox does not indicate any errors. I can also see the GET request is made, and a JSON array is returned. However, I cannot get the array to write to the document or the alert box. Currently, the alert shows:

Data: [object Object] Status: success

Whereas, as far as I understand, 'Data' should display the entire JSON array which is returned by the GET request

I used Google, read through the documentation that came with the API multiple times, I've read through more posts on SO than I can keep count of, but I'm not getting it.

Answer Source

The response is not a single object, it's an array of objects, so you need to index them to access the properties. I show below how to access the first one, but in your real code you would probably loop.

$.getJSON("https://opendata.rdw.nl/resource/m9d7-ebf2.json",{kenteken: kenteken},function(data, status){
    alert("Merk: " + data[0].merk + " Handelsbenaming: " + data[0]. handelsbenaming + " Status: " + status);});