VALID JSON (JavaScript Object Notation)
JSON validator – JSONLint / JSONFormatter
1 2 3 4 5 |
{"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} |
PURE JS CONVERSION
Polyfill for older browsers – JSON3
1 |
var JSON = JSON.stringify(OBJECT, null, 2); |
PHP CONVERSION
Make sure content within the object complies to UTF-8, if not encode it before !
1 |
$JSON = json_encode($OBJECT); |
Even DateTime is nicely encoded :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class User { public $firstname = ""; public $lastname = ""; public $birthdate = ""; } $user = new User(); $user->firstname = "foo"; $user->lastname = "bar"; // Returns: {"firstname":"foo","lastname":"bar"} json_encode($user); $user->birthdate = new DateTime(); /* Returns: { "firstname":"foo", "lastname":"bar", "birthdate": { "date":"2016-02-18 11:42:58", "timezone_type":3, "timezone":"Europe\/Berlin" } } */ json_encode($user); |