$.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.
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);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With