In PHP, you can use json_encode to encode an object as json strings.
$string = json_encode($some_object);
However, PHP has a standard set of data types that are not considered objects (ints, strings, etc.). If you pass the string to json_encode , this returns a string containing the javascript operator, which can be used to define the string.
In a less inconvenient phrasing this
echo json_encode("Hello world, please don't " . '"' . "misuse quote for emphasis " . "or possessive apostrophes' ");
will output this (javascript ready string)
"Hello \n\tworld, please don't \"misuse quote'sor possessive apostrophes' "
Is this part of the behavior of the JSON specification? That is, JSON defines or recommends how the implementation should handle the conversion of native, non-object, data types? Or do you have an opinion about conversion? My reading of the RFC left this as ambiguous, but I'm crap for interpreting these things.
I ask because I'm interested in the likelihood of this behavior disappearing from a future version of the function. that is, if it is codified in the specification somewhere, it is less likely to disappear than if someone thought to add during development.
json javascript php rfc rfc4627
Alan storm
source share