Reputation: 29
How to read JSON to take name and status?
I tried everything and [0] - [1] and without it
[
{
"status": "OK"
},
{
"id": "1",
"name": "name test test"
},
{
"id": "1",
"name": "name test"
},
{
"id": "1",
"name": "test name"
}
]
ajax
$.ajax({
url:'url',
method: 'get',
dataType: 'text',
success: function(response){
if (response.status === "200") {
$.each(response, function(i, data) {
alert(data.name);
});
} else {
alert('error status');
}
}
});
Upvotes: 0
Views: 154
Reputation: 63589
Your Ajax dataType
should be "json":
dataType: "json"
jQuery will automatically parse that returned JSON into a JS object.
And then you can iterate over the objects in the returned array and log the values of the properties you need.
const response=[{status:"OK"},{id:"1",name:"name test test"},{id:"1",name:"name test"},{id:"1",name:"test name"}];
$.each(response, function(i, obj) {
if (obj.status) console.log(obj.status);
if (obj.name) console.log(obj.name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 2
Reputation: 592
In your case because you have data that isn't a match you can go with this:
I am using an if statement to check if there is status then print it else its the field with in your case name and id so it prints that. I am also using success so it only gets to success when the api returns a status of 200.
$.ajax({
url: '/users',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
data.forEach(function(elem){
if(elem.status){
console.log(elem.status)
}else {
console.log(elem.name)
}
})
},
error: function (error) {
console.log(`Error ${error}`);
}
});
and if status is only on the first element in the array then use the index of the array to print it like this:
$.ajax({
url: '/users',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
data.forEach(function(elem, index){
if(index < 1){
console.log(elem.status)
}else {
console.log(elem.name)
}
})
},
error: function (error) {
console.log(`Error ${error}`);
}
});
Upvotes: 0
Reputation: 434
IF you want to use jQuery and read a json, you need to change the dataType property to "json". You can read more about it here
Otherwise, you also can do it without jQuery and it could be more simple today
//...
try {
const response= await fetch('yoururl');
const data = await response.json();
}catch(error){
console.error(error);
}
You can also read more about it here
Upvotes: 0