Michael
Michael

Reputation: 42100

How to handle JSON encoding

I believe that a valid JSON does not contain any encoding information (as opposed to XML, for instance). Is it correct ? Does it have any "standard" encoding (e.g. utf-8) ? How am I supposed to handle the JSON encoding ?

Upvotes: 1

Views: 70

Answers (2)

Paul
Paul

Reputation: 141917

From the JSON RFC, section 3:

3. Encoding

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.

      00 00 00 xx  UTF-32BE
      00 xx 00 xx  UTF-16BE
      xx 00 00 00  UTF-32LE
      xx 00 xx 00  UTF-16LE
      xx xx xx xx  UTF-8

Upvotes: 1

dwettstein
dwettstein

Reputation: 687

You're right. There is no encoding information. But there is also no need for it:

JSON means JavaScript Object Notation. The conclusion is, that you can directly create JavaScript objects from a JSON-text.

{"name":"value"}

This would already be a valid JSON textfile.

An example with an array:

{
  "employees": [
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }
  ]
}

The JSON text format is syntactically identical to the code for creating JavaScript objects.

Because of this similarity, instead of using a parser, a JavaScript program can use the built-in eval() function and execute JSON data to produce native JavaScript objects.

See also here: http://www.w3schools.com/json/

Upvotes: 1

Related Questions