4

I know that PHP provide the JSON_PRETTY_PRINT to format a json data already. What if I want a different format?

$message = array(
    "Open all day" => "Sundays,Saturdays,12-12-2013, 14-10-2013",

    "Availabilty" => array(
        "12/12/2013" => array(
            30,
            60,
            30,
            0
        ),
        "13/12/2013" => array(
            30,
            0,
            30,
            60,
        ),
    ),

);

$json = json_encode($message,JSON_PRETTY_PRINT);

result,

{
    "Open all day": "Sundays,Saturdays,12-12-2013, 14-10-2013",
    "Availabilty": {
        "12\/12\/2013": [
            30,
            60,
            30,
            0
        ],
        "13\/12\/2013": [
            30,
            0,
            30,
            60
        ]
    }
}

But I prefer,

{"Open all day":"
Sundays, 
Saturdays,
Fridays,
12/12/2013, 
14/10/2013, 
04/12/2013
",

"Availability":"
"12/12/2013":[30,60,30,0],
"13/12/2013":[30,60,30,0]
"}

Is that possible? A regex perhaps? Also, I don't want those backslashes - can they be removed?

Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

13

It isn't possible to get that format using json_encode alone.

But to prevent the slashes from being escaped, you could use the JSON_UNESCAPED_SLASHES constant:

$json = json_encode($message,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

See the documentation here.

Demo!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
4

The php has some constants to ensure that the json is valid, so it is recommended to always use these constants to ensure the integrity of information

http://www.php.net/manual/en/json.constants.php

If you want to use without the escape backslashes you can, provided that the json is formatted nicely, but there is no guarantee that, at some point, or some system refuses your json ... So always use the constants that php provides to ensure the integrity of information.

Thiago Valentim
  • 500
  • 6
  • 14