搜尋
首頁後端開發php教程PHP的json_encode分析_PHP教程

PHP的json_encode分析_PHP教程

Jul 14, 2016 am 10:08 AM
encodejsonphpsp優點分析喜歡輸出

 json的优点就不说了,

有个习惯,我在输出json的时候,喜欢用 sprintf 拼成json格式,
 
前两天被朋友说不标准,必须要用json_encode生成的才是标准的json格式,我当然很郁闷啦,
 
用了这么多年了,刚知道 这样做不标准,既然说我不标准,那上面才是标准的json格式?
 
 
 
{a : 'abc'} 
{'a' : 'abc'} 
{a : "abc"} 
{"a" : "abc"} 
那都知道,只有第四种才是标准的json格式。
 
我这么做
 
 
 
$ret_json='{"%s":"%s"}'; 
echo json_encode($ret_json,"a","abc"); 
必然也符合标准。
 
既然如此,那我就要刨根问底,json_encode生成的json格式究竟有什么不同?
上代码
 
 
 
static PHP_FUNCTION(json_encode) 
        zval *parameter; 
        smart_str buf = {0}; 
        long options = 0; 
  
        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", ¶meter, &options) == FAILURE) { 
                return; 
        }    
  
        JSON_G(error_code) = PHP_JSON_ERROR_NONE; 
  
        php_json_encode(&buf, parameter, options TSRMLS_CC); 
  
        ZVAL_STRINGL(return_value, buf.c, buf.len, 1);  
  
        smart_str_free(&buf); 
 
JSON_G(error_code) = PHP_JSON_ERROR_NONE;
是定义的json错误,该错误可以通过json_last_error函数获取,你用过吗?反正我没用过。
php_json_encode是主要的操作
 
 
 
PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ 
        switch (Z_TYPE_P(val)) 
        { 
                case IS_NULL: 
                        smart_str_appendl(buf, "null", 4); //输出NULL 
                        break; 
  
                case IS_BOOL: 
                        if (Z_BVAL_P(val)) { 
                                smart_str_appendl(buf, "true", 4);//输出true 
                        } else { 
                                smart_str_appendl(buf, "false", 5);//输出false 
                        } 
                        break; 
  
                case IS_LONG: 
                        smart_str_append_long(buf, Z_LVAL_P(val));//输出长整形的值 
                        break; 
  
                case IS_DOUBLE: 
                        { 
                                char *d = NULL; 
                                int len; 
                                double dbl = Z_DVAL_P(val); 
  
                                if (!zend_isinf(dbl) && !zend_isnan(dbl)) {//非无穷尽 
                                        len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl); 
                                        smart_str_appendl(buf, d, len); 
                                        efree(d); 
                                } else { 
                                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", dbl); 
                                        smart_str_appendc(buf, '0'); 
                                } 
                       } 
                        break; 
  
                case IS_STRING://字符串 
                        json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options TSRMLS_CC); 
                        break; 
  
                case IS_ARRAY://数组和对象 
                case IS_OBJECT: 
                        json_encode_array(buf, &val, options TSRMLS_CC); 
                        break; 
  
                default: 
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "type is unsupported, encoded as null"); 
                        smart_str_appendl(buf, "null", 4); 
                        break; 
        } 
  
        return; 
很明显,根据不同的类型,会有相应的case。
最复杂的是 字符串 、数组 、对象这三种类型,数组和对象是同一种操作。
先看看字符串吧,很长,注释直接写在代码里。
 
 
 
//options应该是5.3版本之后才支持的,由以下常量组成的二进制掩码: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE.虽然我没用过。。。 
static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC) /* {{{ */ 
        int pos = 0; 
        unsigned short us; 
        unsigned short *utf16; 
  
        if (len == 0) {//如果长度为0,则直接返回 双引号 "" 
                smart_str_appendl(buf, "\"\"", 2); 
                return; 
        } 
  
        if (options & PHP_JSON_NUMERIC_CHECK) {//检测是否为0-9的数字,如果是数字,那么就会直接把数据作为long或double类型返回。 
                double d; 
                int type; 
                long p; 
  
                if ((type = is_numeric_string(s, len, &p, &d, 0)) != 0) { 
                        if (type == IS_LONG) { 
                                smart_str_append_long(buf, p); 
                        } else if (type == IS_DOUBLE) { 
                                if (!zend_isinf(d) && !zend_isnan(d)) { 
                                        char *tmp; 
                                        int l = spprintf(&tmp, 0, "%.*k", (int) EG(precision), d); 
                                        smart_str_appendl(buf, tmp, l); 
                                        efree(tmp); 
                                } else { 
                                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", d); 
                                        smart_str_appendc(buf, '0'); 
                                } 
                        } 
                        return; 
                } 
  
        } 
  
        utf16 = (unsigned short *) safe_emalloc(len, sizeof(unsigned short), 0); 
        len = utf8_to_utf16(utf16, s, len); //这里会对你输入的值一次处理转成对应的Dec码,比如1是49,a是97这样的,保存到utf16中。 
        if (len
                if (utf16) { 
                        efree(utf16); 
                } 
                if (len
                        JSON_G(error_code) = PHP_JSON_ERROR_UTF8; 
                        if (!PG(display_errors)) { 
                                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid UTF-8 sequence in argument"); 
                        } 
                        smart_str_appendl(buf, "null", 4); 
                } else { 
                        smart_str_appendl(buf, "\"\"", 2); 
                } 
                return; 
        } 
  
        smart_str_appendc(buf, '"'); //输入 \" 
  
//下面这一段代码就是将一些特殊字符转义如 双引号,反斜线等等 
        while (pos
        { 
                us = utf16[pos++]; 
  
                switch (us) 
                { 
                        case '"': 
                                if (options & PHP_JSON_HEX_QUOT) { 
                                        smart_str_appendl(buf, "\\u0022", 6); 
                                } else { 
                                        smart_str_appendl(buf, "\\\"", 2); 
                                } 
                                break; 
  
                        case '\\': 
                                smart_str_appendl(buf, "\\\\", 2); 
                                break; 
case '/': 
                                smart_str_appendl(buf, "\\/", 2); 
                                break; 
  
                        case '\b': 
                                smart_str_appendl(buf, "\\b", 2); 
                                break; 
  
                        case '\f': 
                                smart_str_appendl(buf, "\\f", 2); 
                                break; 
  
                        case '\n': 
                                smart_str_appendl(buf, "\\n", 2); 
                                break; 
  
                        case '\r': 
                                smart_str_appendl(buf, "\\r", 2); 
                                break; 
  
                        case '\t': 
                                smart_str_appendl(buf, "\\t", 2); 
                                break; 
  
                        case '
                                if (options & PHP_JSON_HEX_TAG) { 
                                        smart_str_appendl(buf, "\\u003C", 6); 
                                } else { 
                                        smart_str_appendc(buf, '
                                } 
                                break; 
  
                        case '>': 
                                if (options & PHP_JSON_HEX_TAG) { 
                                        smart_str_appendl(buf, "\\u003E", 6); 
                                } else { 
                                        smart_str_appendc(buf, '>'); 
                                break; 
  
                        case '&': 
                                if (options & PHP_JSON_HEX_AMP) { 
                                        smart_str_appendl(buf, "\\u0026", 6); 
                                } else { 
                                        smart_str_appendc(buf, '&'); 
                                } 
                                break; 
  
                        case '\'': 
                                if (options & PHP_JSON_HEX_APOS) { 
                                        smart_str_appendl(buf, "\\u0027", 6); 
                                } else { 
                                        smart_str_appendc(buf, '\''); 
                                } 
                                break; 
  
                        default: //一直到这里,没有特殊字符就会把值append到buf中 
                                if (us >= ' ' && (us & 127) == us) { 
                                        smart_str_appendc(buf, (unsigned char) us); 
                                } else { 
                                        smart_str_appendl(buf, "\\u", 2); 
                                        us = REVERSE16(us); 
  
                                        smart_str_appendc(buf, digits[us & ((1
                                        us >>= 4; 
                                        smart_str_appendc(buf, digits[us & ((1
                                        us >>= 4; 
                                        smart_str_appendc(buf, digits[us & ((1
                                        us >>= 4; 
                                        smart_str_appendc(buf, digits[us & ((1
                                } 
                                break; 
                } 
        } 
        smart_str_appendc(buf, '"'); //结束 双引号。 
        efree(utf16); 
再来看看数组和对象,也很简单,
 
 
 
static void json_encode_array(smart_str *buf, zval **val, int options TSRMLS_DC) /* {{{ */ 
        int i, r; 
        HashTable *myht; 
  
        if (Z_TYPE_PP(val) == IS_ARRAY) { 
                myht = HASH_OF(*val); 
                r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : json_determine_array_type(val TSRMLS_CC); 
        } else { 
                myht = Z_OBJPROP_PP(val); 
                r = PHP_JSON_OUTPUT_OBJECT; 
        }    
  
        if (myht && myht->nApplyCount > 1) { 
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); 
                smart_str_appendl(buf, "null", 4); 
                return; 
        } 
//开始标签 
        if (r == PHP_JSON_OUTPUT_ARRAY) { 
                smart_str_appendc(buf, '['); 
        } else { 
                smart_str_appendc(buf, '{'); 
        }    
  
        i = myht ? zend_hash_num_elements(myht) : 0; 
  
        if (i > 0) 
        { 
                char *key; 
                zval **data; 
                ulong index; 
                uint key_len; 
                HashPosition pos; 
                HashTable *tmp_ht; 
                int need_comma = 0; 
  
                zend_hash_internal_pointer_reset_ex(myht, &pos); 
//便利哈希表 
                for (;; zend_hash_move_forward_ex(myht, &pos)) { 
                        i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); 
                        if (i == HASH_KEY_NON_EXISTANT) 
                                break; 
  
                        if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS) { 
                                tmp_ht = HASH_OF(*data); 
                                if (tmp_ht) { 
                                        tmp_ht->nApplyCount++; 
                                } 
  
                                if (r == PHP_JSON_OUTPUT_ARRAY) { 
                                        if (need_comma) { 
                                                smart_str_appendc(buf, ','); 
                                        } else { 
                                                need_comma = 1; 
                                        } 
//将值append到 buf中 
                                        php_json_encode(buf, *data, options TSRMLS_CC); 
                                } else if (r == PHP_JSON_OUTPUT_OBJECT) { 
                                        if (i == HASH_KEY_IS_STRING) { 
                                                if (key[0] == '\0' && Z_TYPE_PP(val) == IS_OBJECT) { 
                                                        /* Skip protected and private members. */ 
                                                        if (tmp_ht) { 
                                                                tmp_ht->nApplyCount--; 
                                                        } 
                                                        continue; 
                                                } 
  
                                                if (need_comma) { 
                                                        smart_str_appendc(buf, ','); 
                                                } else { 
                                                        need_comma = 1; 
                                                } 
  
                                                json_escape_string(buf, key, key_len - 1, options & ~PHP_JSON_NUMERIC_CHECK TSRMLS_CC); 
                                                smart_str_appendc(buf, ':'); 
  
                                                php_json_encode(buf, *data, options TSRMLS_CC); 
                                        } else { 
                                                if (need_comma) { 
                                                        smart_str_appendc(buf, ','); 
                                                } else { 
                                                        need_comma = 1; 
                                                } 
  
                                                smart_str_appendc(buf, '"'); 
                                                smart_str_append_long(buf, (long) index); 
                                                smart_str_appendc(buf, '"'); 
                                                smart_str_appendc(buf, ':'); 
  
                                                php_json_encode(buf, *data, options TSRMLS_CC); 
                                        } 
                                } 
  
                                if (tmp_ht) { 
                                        tmp_ht->nApplyCount--; 
                                } 
                        } 
                } 
        } 
//结束标签 
        if (r == PHP_JSON_OUTPUT_ARRAY) { 
                smart_str_appendc(buf, ']'); 
        } else { 
                smart_str_appendc(buf, '}'); 
        } 
通过简单分析,证明了一个问题,跟我上面用sprintf的方法其实是一样的,都是拼接字符串,

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477721.htmlTechArticlejson的优点就不说了, 有个习惯,我在输出json的时候,喜欢用 sprintf 拼成json格式, 前两天被朋友说不标准,必须要用json_encode生成的才是标...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
繼續使用PHP:耐力的原因繼續使用PHP:耐力的原因Apr 19, 2025 am 12:23 AM

PHP仍然流行的原因是其易用性、靈活性和強大的生態系統。 1)易用性和簡單語法使其成為初學者的首選。 2)與web開發緊密結合,處理HTTP請求和數據庫交互出色。 3)龐大的生態系統提供了豐富的工具和庫。 4)活躍的社區和開源性質使其適應新需求和技術趨勢。

PHP和Python:探索他們的相似性和差異PHP和Python:探索他們的相似性和差異Apr 19, 2025 am 12:21 AM

PHP和Python都是高層次的編程語言,廣泛應用於Web開發、數據處理和自動化任務。 1.PHP常用於構建動態網站和內容管理系統,而Python常用於構建Web框架和數據科學。 2.PHP使用echo輸出內容,Python使用print。 3.兩者都支持面向對象編程,但語法和關鍵字不同。 4.PHP支持弱類型轉換,Python則更嚴格。 5.PHP性能優化包括使用OPcache和異步編程,Python則使用cProfile和異步編程。

PHP和Python:解釋了不同的範例PHP和Python:解釋了不同的範例Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP和Python:深入了解他們的歷史PHP和Python:深入了解他們的歷史Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

在PHP和Python之間進行選擇:指南在PHP和Python之間進行選擇:指南Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP和框架:現代化語言PHP和框架:現代化語言Apr 18, 2025 am 12:14 AM

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHP的影響:網絡開發及以後PHP的影響:網絡開發及以後Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中