How to parse JSON in JS/JQ?

Good day!

Right to the point:
There is a search box, when you enter into it anything is sent an ajax request to the page /ajax/xxx.php
She, in turn, gives a json via json_encode, the answer may be different if some sort of error:

Php code:
$status = 'error';
$array = array(
 "status" => $status,
 "data" => array(
 "message" => "KAKATOE"
)
);


The resulting json:
{
 "status": "error",
 "data": {
 "message": "KAKATOE"
}
}


But if there was a match in the database:

Php code:
$k = 1;
$array = array();
while ($row = $result->fetch_assoc()) {
 $array[$k] = array(
 "id" => $row['id'],
 "name" => $row['name']
);
$k++;
}


The resulting json:
{
 "1": {
 "id": "1",
 "name": "1"
},
 "2": {
 "id": "2",
 "name": "1"
}
}


Here he ajax request:
function search() {
var data = {
 search: $('#search').val()
}
$.ajax({
 type: 'POST',
 dataType: 'json',
 url: '/ajax/xxx.php',
 data: data,
 success: function(data) {
search_answer(data);
}
});
};


But the function that "parses" the answer is:
search_answer function(res) {
// output the information
if (res.status == 'error') {
 if (res.data.message == 'ERROR_2') {
$(".error").text("ERROR_2");
}
 if (res.data.message == 'ERROR_1') {
$(".error").text("ERROR_1");
}
}
};


Understand that fierce bydlokod, but please help, I can not understand how to derive the results.

UPD. If the received id and name then print them in a div with the class answer. As I understand it you need a loop to iterate through the resulting array, but can't figure out how to make one.
June 3rd 19 at 20:57
1 answer
June 3rd 19 at 20:59
Instead of dataType: 'text' to insert dataType: 'json' and the body of the function success need not JSON.parse()
thank you for the correction, but how do I display the data found in html? - nikita.Stracke commented on June 3rd 19 at 21:02

Find more questions by tags JavaScriptjQueryJSON