Why does my JSON array turn into an object?

60 views Asked by At

I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process.

test_bots.json contains this JSON array:

["John","Vladimir","Toni","Joshua","Jessica"]

My code looks like this:

$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);

if(in_array($good, $good_arr)){
        $key = array_search($good, $good_arr);
         unset($good_arr[$key]);

        $good_arr2 = json_encode($good_arr);
        file_put_contents('test_bots.json',$good_arr2); 
    }

The output that's saved is:

{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}

but I want the output to look like:

["John","Vladimir","Joshua","Jessica"]

I tried to unserialize the array before saving it, but it's not working.

Why is this happening?

1

There are 1 answers

0
Don't Panic On BEST ANSWER

In order for json_encode to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. (See example #4 in the PHP manual for json_encode.)

You can accomplish this in your code by using array_values, which will reindex the array after you have removed one of the items.

$good_arr2 = json_encode(array_values($good_arr));