26
1

用js的json_decode解决JSON中文编码问题

最近写个程序 用jquery读取PHP的json信息,一直没注意中文的问题,今天输出中文居然出现类似”\u6210\u529f”的字符,网上查了一下,因为我页面全部用utf8编码,不存在meta的问题.

最后找到一个js版的json_decode,果然有效,贴一下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function json_decode (str_json) { 
    var json = this.window.JSON;
    if (typeof json === 'object' && typeof json.parse === 'function') {
        try {
            return json.parse(str_json);
        } catch(err) {
            if (!(err instanceof SyntaxError)) {
                throw new Error('Unexpected error type in json_decode()');
            }
            this.php_js = this.php_js || {};
            this.php_js.last_error_json = 4; // usable by json_last_error()
            return null;
        } 
    }    
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }
    if ((/^[\],:{}\s]*$/).
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
        j = eval('(' + text + ')'); 
        return j;
    }
 
    this.php_js = this.php_js || {};
    this.php_js.last_error_json = 4; // usable by json_last_error()
    return null;
}

原出处:http://phpjs.org/functions/json_decode:456

相关日志

当前没有评论!

第一个在本文留言。

发表评论

名字(必须)
邮箱(必须),(永不被公布)
网址(建议)

字体为 粗体 是必填项目,邮箱地址 永远不会 公布。

允许部分 HTML 代码:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
URLs(网站链接)必须完整有效 (比如: http://www.vpnall.com),所有标签都必须完整的关闭。

超出部分系统将会自动分段及换行。

请保证评论内容是与日志或 Blog 内容相关的,灌水、攻击性或不恰当的评论 可能 会被编辑或删除。