Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JSON elements from javascript

$.getJSON('http://23.21.128.153:3000/api/v1/holidays', function(data){
        alert("this: " + data.holiday[0].name);
 });

I'm trying to access the "name" attribute of the first element of my JSON response but without success, can anyone tell me what I'm doing wrong.

like image 757
Luis D Urraca Avatar asked Jun 01 '12 00:06

Luis D Urraca


People also ask

How do I read a JSON file in JavaScript?

To fix this error, we need to add the file type of JSON to the import statement, and then we'll be able to read our JSON file in JavaScript: import data from './data. json' assert { type: 'JSON' }; console. log(data);

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

Can you use JSON in JavaScript?

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.

How do you parse an array of JSON objects?

Parsing JSON Data in JavaScript In JavaScript, you can easily parse JSON data received from the web server using the JSON. parse() method. This method parses a JSON string and constructs the JavaScript value or object described by the string. If the given string is not valid JSON, you will get a syntax error.


1 Answers

Try this:

data[0].holiday.name

The data looks like this:

[
  {
    "holiday":{
      "id":1,
      "date":"2012-05-01",
      "name":"Dia del trabajo",
      "description":"",
      "country_id":1,
      "moved_date":"2012-04-30"
    }
  },
  {
    "holiday":{...}
  },
...]

So, you need to select the first element from the main array (data[0]), then get its holiday property (data[0].holiday), and then get its name property.

like image 111
cambraca Avatar answered Oct 02 '22 20:10

cambraca