Search code examples
javascriptphpjqueryjsonutf8-decode

how parse utf-8 json in jquery


I have encode a Persian name in php file . before encoding it is displayed correct and after encoding it converts to utf-8 characters. and i am receiving it in java Script (jQuery) By Ajax.

sample.php :

json_encode('نام خانوادگی ');

//after encode: "\u06a9\u0627\u0638\u0645\u06a9\u06cc"

Js:
JSON.parse(response)
// it is still in this form: \u06a9\u0627\u0638\u0645 \u06a9\u06cc

how do I parse this json so that i can have it in its original form?


Solution

  • This has nothing to do with UTF-8, but with Unicode. The difference is:

    var original = "\u06a9\u0627\u0638\u0645\u06a9\u06cc"
    var encoded = "\\u06a9\\u0627\\u0638\\u0645\\u06a9\\u06cc"
    

    You have to convert the string representing the Unicode notation back to the original string. Use this:

    var r = encoded.replace(/\\u(....)/gi, function(m,v){
        return String.fromCharCode(parseInt(v,16))
    })
    alert(r)