How to set encoding in .getJSON jQuery How to set encoding in .getJSON jQuery json json

How to set encoding in .getJSON jQuery


If you want to use $.getJSON() you can add the following before the call :

$.ajaxSetup({    scriptCharset: "utf-8",    contentType: "application/json; charset=utf-8"});

You can use the charset you want instead of utf-8.

The options are explained here.

contentType : When sending data to the server, use this content-type. Default is application/x-www-form-urlencoded, which is fine for most cases.

scriptCharset : Only for requests with jsonp or script dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

You may need one or both ...


I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have <div id="success"></div> and <div id="error"></div> in the html):

$.ajax({    type: "POST",    url: "SomePage.aspx/GetSomeObjects",    contentType: "application/json; charset=utf-8",    dataType: "json",    data: "{id: '" + someId + "'}",    success: function(json) {        $("#success").html("json.length=" + json.length);        itemAddCallback(json);    },    error: function (xhr, textStatus, errorThrown) {        $("#error").html(xhr.responseText);    }});

I actually just had to do this about an hour ago, what a coincidence!


You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:

  • If the page is simple if text / html
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.0010  0a 43 6f 6e 74 65 6e 74  2d 54 79 70 65 3a 20 74   .Content -Type: t0020  65 78 74 2f 68 74 6d 6c  0d 0a 43 61 63 68 65 2d   ext/html ..Cache-0030  43 6f 6e 74 72 6f 6c 3a  20 6e 6f 2d 63 61 63 68   Control:  no-cach
  • If the page is of the type including custom JSON with MIME "charset = ISO-8859-1"
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.0010  0a 43 61 63 68 65 2d 43  6f 6e 74 72 6f 6c 3a 20   .Cache-C ontrol: 0020  6e 6f 2d 63 61 63 68 65  0d 0a 43 6f 6e 74 65 6e   no-cache ..Conten0030  74 2d 54 79 70 65 3a 20  74 65 78 74 2f 68 74 6d   t-Type:  text/htm0040  6c 3b 20 63 68 61 72 73  65 74 3d 49 53 4f 2d 38   l; chars et=ISO-80050  38 35 39 2d 31 0d 0a 43  6f 6e 6e 65 63 74 69 6f   859-1..C onnectio

Why is that? because we can not put on the page of JSON a goal like this:

In my case I use the manufacturer Connect Me 9210 Digi:

  • I had to use a flag to indicate that one would use non-standard MIME: p-> theCgiPtr-> = fDataType eRpDataTypeOther;
  • It added the new MIME in the variable: strcpy (p-> theCgiPtr-> fOtherMimeType, "text / html;charset = ISO-8859-1 ");

It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...