In PHP, you can use json_encode
to encode an object as a json string.
$string = json_encode($some_object);
However, PHP has the standard slew of datatypes which are not considered objects (ints, strings, etc.) If you pass in a string to json_encode
, this returns a string that contains a javascript statement that could be used to define the string.
In less awkward phrasing, this
echo json_encode("Hello
world, please don't " . '"' . "misuse quote's for emphasis " . "or possessive apostrophes' ");
will output this (a javascript ready string)
"Hello \n\tworld, please don't \"misuse quote'sor possessive apostrophes' "
Is this behavior part of the JSON specification? That is, does JSON define or recommend how an implementation should handle conversion of native, non-object, datatypes? Or even have an opinion on conversion at all? My reading of the RFC left this as ambiguous, but I'm crap at interpreting these things.
I ask because I'm interested in the likelihood of this behavior disappearing from a future version of the function. i.e. If it's codified in a specification somewhere, it's less likely to disappear than if it was a one off someone thought to add on during development.
JSON doesn't care about native types at all. It is up to the developer of the JSON library or functionality as to how the JSON is translated to and from types that the programming language can use/understand.
You are right alan, the RFC is not clear enough on this issue.
On one hand, on the link to the RFC that you provide it says on the second paragraph of the introduction:
But on the other hand when you continue to the paragraph That talks about the actual JSON grammar it says:
So based on the grammar you can say that
'a string'
does not qualify as valid JSON-text.Personally I would prefer to see the grammar "fixed" to say
JSON-text = value
thus making any offalse / null / true / object / array / number / string
become valid JSON-text.If you want to be strict for now, I would go with the semantics of the grammar.
I will send Douglas Crockford a link to this question maybe he can add some useful info.