PHP Json_encode Analysis _php Tutorial

Source: Internet
Author: User
The advantages of JSON do not say, there is a habit, I in the output JSON, like to use sprintf to spell JSON format, the first two days by friends said not standard, must be used Json_encode generated is the standard JSON format, I am of course very depressed, with so many years, just know This is not standard, since said I do not standard, it is the standard JSON format? {A: ' abc '} {' A ': ' ABC '} {A: "abc"} {"A": "ABC"} All know that only the fourth type is the standard JSON format. I do this $ret _json= ' {'%s ': '%s '} '; Echo Json_encode ($ret _json, "A", "abc"); must also conform to the standard. That being the case, I'm going to get to the json_encode. What is the difference between the JSON format generated? On the Code static Php_function (json_encode) {zval *parameter; smart_str buf = {0}; long options = 0; if (zend_parse_parameters (Z End_num_args () tsrmls_cc, "Z|l", &parameter, &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 (&AMP;BUF); } json_g (Error_code) = Php_json_error_none; is a defined JSON error that can be obtained through the Json_last_error function, have you ever used it? I didn't use them anyway. Php_json_encode is the primary operation Php_json_api void Php_json_encode (Smart_str *buf, zval *val, int options tsrmls_dc)/* {{{* * * Swit CH (z_type_p (val)) {Case Is_null:smart_str_appendl (buf, "NULL", 4); Output null break; Case Is_bool:if (Z_bval_p (val)) {Smart_str_appendl (buf, "true", 4);//Output true} else {Smart_str_appendl (buf, "false", 5); Output false} break; Case Is_long:smart_str_append_long (buf, Z_lval_p (val));//output long shaping value break; Case is_double: {char *d = NULL, int len, DOUBLE dbl = Z_dval_p (val), if (!zend_isinf (dbl) &&!zend_isnan (dbl)) { Non-infinite 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://String json_escape_string (buf, Z_strval_p (Val), Z_strlen_p (val), Options TSRMLS_CC); Break Case is_array://Array and object 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; It is obvious that depending on the type, there will be a corresponding CAse. The most complex are three types of strings, arrays, objects, and arrays and objects are the same operation. First look at the string, very long, the comments are written directly in the code. The options should be supported after version 5.3, a binary mask consisting of the following constants: 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. Although I didn't use it. 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) {//If the length is 0, return the double quotation mark "" Smart_str_appendl (buf, "\" \ "", 2); return;} if (Options & Php_json_numeric_check {//detects if the number is 0-9, and if it is a number, it returns the data directly as a long or double type. 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); The value you enter will be processed to the corresponding DEC code, for example, 1 is 49,a 97, and saved to UTF16. if (len <= 0) {//If Len is less than 0 indicates an error. If you use Json_encode to process GBK encoding, you will hang up here. if (UTF16) {efree (UTF16),} if (Len < 0) {Json_g (error_code) = Php_json_error_utf8; PG (display_errors)) {php_error_docref (NULL tsrmls_cc, e_warning, "Invalid UTF-8 sequence in Argument");} Smart_str_appe NDL (buf, "null", 4); } else {Smart_str_appendl (buf, "\" \ "", 2);} return; } SMART_STR_APPENDC (buf, ' "'); Input \ "//The following paragraph of code is to escape some special characters such as double quotes, backslashes and so on (Pos < len) {us = utf16[pos++]; switch (US) {case '" ': if (Options &amp ; 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://All the time, no special characters will append the value to BUF if (US >= ' && (US & 127) = = us) {SMART_STR_APPENDC (buf, Unsigne D char) US); } else {Smart_str_appendl (buf, "\\u", 2); US = REVERSE16 (US); SMART_STR_APPENDC (buf, Digits[us & ((1 << 4)-1)]); US >>= 4; SMART_STR_APPENDC (buf, Digits[us & ((1 << 4)-1)]); US >>= 4; SMART_STR_APPENDC (buf, Digits[us & ((1 << 4)-1)]); US >>= 4; SMART_STR_APPENDC (buf, Digits[us & ((1 << 4)-1)]); } break; }} SMART_STR_APPENDC (buf, ' "'); Ends double quotation marks. Efree (UTF16); Then look at the arrays and objects, also very simple, static void Json_encode_array (Smart_str *buf, zval **val, int options tsrmls_dc)/* {{{* */{int i, r; H Ashtable *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_er Ror_docref (NULL tsrmls_cc, e_warning, "recursion detected"); Smart_str_appendl (buf, "null", 4); Return }//start tag 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); Convenient hash table 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;}//value append to BU F Medium Php_json_encode (buf, *data, Options TSRMLS_CC); } else if (r = = Php_json_output_object) {if (i = = hash_key_is_string) {if (key[0] = = ' + ' && z_type_pp (val) = = I S_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--;}} }}//end tag if (r = = Php_json_output_array) {SMART_STR_APPENDC (buf, '] '); } else {SMART_STR_APPENDC (buf, '} '); }} through a simple analysis, proved a problem, with me above using the sprintf method is actually the same, is a concatenation of strings,

http://www.bkjia.com/PHPjc/477721.html www.bkjia.com true http://www.bkjia.com/PHPjc/477721.html techarticle The advantages of JSON do not say, there is a habit, I in the output JSON, like to use sprintf to spell JSON format, the first two days by friends said nonstandard, you must use Json_encode generated is the superscript ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.