0

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');
        }
     }
  });
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Secux
  • 19
  • 7
  • Are you talking about the HTTP status, or the status in the first object of the response? – Andy Aug 31 '21 at 19:38
  • first object and id, name – Secux Aug 31 '21 at 19:41
  • a) [$.ajax - dataType](https://stackoverflow.com/q/2722750/215552) You must use `dataType: 'json'` if you want it to parse your data as JSON. b) if you're asking how to get data from that arrray, [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383/215552) – Heretic Monkey Aug 31 '21 at 19:42
  • The JSON data is an array of objects, and you are accessing it as an object. – Invizi Aug 31 '21 at 19:50

3 Answers3

2

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>
Andy
  • 61,948
  • 13
  • 68
  • 95
0

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.

For Each

$.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}`);
    }
});
Schnecke
  • 502
  • 1
  • 6
  • 18
  • You should explain what you've changed. – Andy Aug 31 '21 at 19:30
  • I'm testing what you offered me.. not working – Secux Aug 31 '21 at 19:38
  • does your data return json or text? console.log(typeof data) – Schnecke Aug 31 '21 at 19:39
  • this console.log(data); - return [object Object],[object Object],[object Object],[object Object] .... this console.log(elem.status) - return - OK (this work) ... this return console.log(elem.name) - undefined – Secux Aug 31 '21 at 19:39
  • dataType: "json", – Secux Aug 31 '21 at 19:39
  • can you give me the api you are trying to call, so i can test myself – Schnecke Aug 31 '21 at 19:41
  • @Schnecke - PHP $response[] = array('status' => 'OK'); $response[] = array( "id" => $row['userID'], "name" => $row['name'], ); return json_encode($response); PHP and header is set Content-Type: application/json – Secux Aug 31 '21 at 19:44
  • I cant run the code you sent, so i guess just in the first console.log do this console.log(typeof data) to see if you get back a string or array or object – Schnecke Aug 31 '21 at 19:51
  • i use array before i do it json – Secux Aug 31 '21 at 20:06
0

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

jircdeveloper
  • 424
  • 2
  • 17