[Code] PHP json

Source: Internet
Author: User
I don't want to talk about the advantages of json. I have a habit. When I output json, I like to use sprintf to construct the json format. I was told by my friends that it was not standard two days ago, the standard json format must be generated using json_encode. Of course, I am very depressed. After so many years of use, I just learned that this is not a standard. Since I am not a standard, is the above standard json format?

I don't want to talk about the advantages of json. I have a habit. When I output json, I like to use sprintf to construct the json format. I was told by my friends that it was not standard two days ago, the standard json format must be generated using json_encode. Of course, I am very depressed. After so many years of use, I just learned that this is not a standard. Since I am not a standard, is the above standard json format?

JsonThe advantages,


I like to use sprintf to spell json format when outputting json,


Two days ago, I was told that it was not standard. The standard json format must be generated using json_encode. Of course, I am very depressed,


After so many years of use, I just learned that this is not a standard. Since I am not a standard, is the above standard json format?


{a : 'abc'}{'a' : 'abc'}{a : "abc"}{"a" : "abc"}


We all know that only the fourth type is the standard json format.


I am doing this


$ret_json='{"%s":"%s"}';echo json_encode($ret_json,"a","abc");


It must also comply with standards.

In this case, I have to answer the question. What is the difference in the json format generated by json_encode?
Code on

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;
Is a defined json error. This error can be obtained through the json_last_error function. Have you used this error? I have never used it.
Php_json_encode is the main operation

PHP_JSON_API void trim (smart_str * buf, zval * val, int options TSRMLS_DC)/* {*/{switch (Z_TYPE_P (val) {case IS_NULL: smart_str_appendl (buf, "null", 4); // outputs 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 the break of the long integer; ca Se 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 struct (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 ;}


Obviously, there will be corresponding cases based on different types.
The most complex types are string, array, and object. arrays and objects are the same operation.
Let's take a look at the string first. It's very long. Comments are directly written in the code.

// Options should be supported only after version 5.3. The binary mask composed of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, signature, JSON_NUMERIC_CHECK, signature, expires, JSON_FORCE_OBJECT, and signature. although I have never used 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, double quotation marks "" smart_str_appendl (buf, "\" \ "", 2) are directly returned ); return;} if (options & PHP_JSON_NUMERIC_CHECK) {// check whether it is a 0-9 number. if it is a number, the data is directly returned 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, le N); // here, the input value is converted to the corresponding Dec Code, for example, 1 is 49, a is 97, and saved to utf16. If (len <= 0) {// if len is smaller than 0, an error occurs. If you use json_encode to process GBK encoding, it will be suspended here. If (utf16) {efree (utf16);} if (len <0) {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, '"'); // input \"



// The following code escapes special characters, such as double quotation marks and backslash.
While (pos <len) {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: // until here, if (us> = ''& (us & 127) = us) {smart_str_appendc (buf, (unsigned char) us);} else {sm Art_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, '"'); // end double quotation marks. Efree (utf16 );}


Let's take a look at arrays and objects, which is also very simple,




After a simple analysis, it is proved that the sprintf method is the same as that used above, and all of them are concatenated strings,


In addition, sprintf should be encouraged to splice json formats for performance purposes,


Because json_encode performs many loop operations, and the consumed performance is linear.


Of course, this article only analyzes the simplest case objectively. If the data is an array or other complex data, we recommend using json_encode.


The above is the json_encode Analysis of PHP in this article.Php developersThanks for reading this article.

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.