phpjsonphp-7.0

Response with unwanted new lines appears while encoding array to JSON


Having an array printed with print_r method:

Array
(
    [0] => Array
        (
            [id] => 44
            [item_level] => 0
            [position] => 10
            [parent_position] => 
            [title] => PHP Tutorial
            [qty] => 0
            [comment] => 
            [status] => 
            [unit] => 
        )

    [1] => Array
        (
            [id] => 46
            [item_level] => 1
            [position] => 20
            [parent_position] => 
            [title] => Algorithms
            [qty] => 1
            [comment] => 
            [status] => 
            [unit] => 
        )

    [2] => Array
        (
            [id] => 48
            [item_level] => 2
            [position] => 30
            [parent_position] => 20
            [title] => PHP and MySQL Databases
            [qty] => 1
            [comment] => 
            [status] => 
            [unit] => 
        )
)

I'm trying to encode it as JSON using either:

json_encode($array, JSON_NUMERIC_CHECK);
json_encode($array);

The output in both cases is the following though:

[{"id":"44","item_level":0,"position":10,"parent_position":"","product_id":"","title":"PHP
Tutorial","qty":0,"comment":"","status":"","unit":""},{"id":"46","item_level":1,"position":20,"parent_position":"","title":"Algorithms","qty":1,"comment":"","status":"","unit":""},{"id":"48","item_level":2,"position":30,"parent_position":20,"title":"PHP
and MySQL
Databases","qty":1,"comment":"","status":"","unit":""}]

Yes, there are the newline characters put between some, but not all, space-separated words. In Postman, the response arrives broken into multiple lines, the same happens when my frontend gets this kind of response, causing it to report JSON parsing error.

How to transform the array to JSON format properly?

PHP version here is 7.0.33.


Solution

  • Tried to look for any non-printable characters that might have been added on the way, as it was suggested in the comments, but wasn't able to locate any.

    Anyway, pretty printing solved the issue in a satisfying way:

    json_encode($array, JSON_PRETTY_PRINT);
    

    The only thing to be considered, is casting numbers to proper types on arrival to frontend, since JSON_PRETTY_PRINT prints out all of them as strings (i.e. {"quantity": "1"}).