'How to loop through JSON object with an array with backslashes inside in Jquery/Javascript from AJAX call

I have an array where I want to loop through the array inside the JSON and show the data in the table based on the nationalities in the array. The problem is that the array data contains backslashes and I can't loop through it. I retrieve the data with an AJAX call from my PHP file.

PHP:

$arr 

if (!empty($arr)) {
        echo json_encode($arr);
      // print_r($arr);
    } else{
        $errors = 'No data available.';
    }
            exit;

If I print_r() I see: Array ( [0] => stdClass Object ( [company] => John Comp [pro_countries] => ["BR","ES","FR"])

If I use echo json_encode my echo looks like but I can print company in my Jquery: [{"company":"John Comp","nationality":"[\"BR\",\"ES\",\"FR\"]"}]

But if I use print_r($arr) the slashes disappear but I can't seem to print the company in Jquery: [{"company":"John Comp","nationality":"["BR","ES","FR"]"}]

If I use Print_r() Then my AJAX call in JQuery goes straight to the error response. JQuery:

 $.ajax({
 type: 'GET',
            url: 'testurl',
            dataType: 'json',
            processData: false,
            cache: false,
            success: function (response){
            

             response.nationality.forEach((item)=>{

            });

I also tried:

$.ajax({
 type: 'GET',
            url: 'testurl',
            dataType: 'json',
            processData: false,
            cache: false,
            success: function (response){

var data = JSON.parse(response);

data.nationality.forEach((item)=>{

  });

What I want after the loop:

enter image description here



Solution 1:[1]

nationality is a JSON string, you need to parse it so you can loop over it.

JSON.parse(response.nationality).forEach(item => ...)

I'm not sure why you encoded nationality in the first place. You should just make it an ordinary PHP array, and then it will be encoded as part of $arr.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar