Php method for determining whether the format is json _ php instance

Source: Internet
Author: User
This article describes how to determine whether php is in json format. For more information, remember that json_encode returns a string while json_decode returns an object.

Determine that the data is not in JSON format:

The code is as follows:


Function is_not_json ($ str ){
Return is_null (json_decode ($ str ));
}

Determine that the data is legal json data: (PHP version is later than 5.3)

The code is as follows:


Function is_json ($ string) {www.jb51.net
Json_decode ($ string );
Return (json_last_error () = JSON_ERROR_NONE );
}

The json_last_error () function returns an error during data encoding/decoding.

Note: The json codec operation string must be UTF8

Example

The code is as follows:


/**
* Parse json strings
* @ Param type $ json_str
* @ Return type
*/
Function analyJson ($ json_str ){
$ Json_str = str_replace ('\', '', $ json_str );
$ Out_arr = array ();
Preg_match ('/{. *}/', $ json_str, $ out_arr );
If (! Empty ($ out_arr )){
$ Result = json_decode ($ out_arr [0], TRUE );
} Else {
Return FALSE;
}
Return $ result;
}


If it is not json, false is returned.

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.