Does JSON support native type conversion support?

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.

+1
json javascript php rfc rfc4627
source share
2 answers

JSON is not at all interested in native types. It depends on the developer of the JSON library or the functionality regarding how JSON is translated into and out of types that the programming language can use / understand.

+3
source share

You are right alan, the RFC is not clear enough about this.

On the one hand, the link to the RFC that you provide says in the second paragraph of the introduction:

JSON can represent four primitive types (strings, numbers, Boolean and zero) and two structured types (objects and arrays).

But, on the other hand, when you continue the paragraph that talks about JSON grammar itself, it says:

JSON text is a serialized object or array.
JSON-text = object / array

So, based on the grammar, you can say that 'a string' not a valid JSON text.

Personally, I would prefer the grammar to โ€œcommitโ€ to say JSON-text = value , which makes any of false / null / true / object / array / number / string valid JSON text.

If you want to be strict now, I would go with the semantics of grammar.

I will send Douglas Crockford a link to this question, maybe he can add useful information.

+1
source share

All Articles