Home  >  Article  >  Backend Development  >  How to determine whether it is in json format in PHP7?

How to determine whether it is in json format in PHP7?

WBOY
WBOYOriginal
2016-09-30 09:37:321718browse

A function I found online:

<code>function is_json($string) 
{
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

$str = '{id:23,name:"test"}';
$str = "{'id':23,'name':'test'}";
为什么在PHP7,均不是合法的json格式呢??
有没有靠谱的方法??</code>

Reply content:

A function I found online:

<code>function is_json($string) 
{
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

$str = '{id:23,name:"test"}';
$str = "{'id':23,'name':'test'}";
为什么在PHP7,均不是合法的json格式呢??
有没有靠谱的方法??</code>

In JSON format, both key and value must be in double quotes...

return json_encode($json)!==false

PHP7 adopts stricter JSON rules, single quotes can no longer be used for references and field names.

<code>var arr = {id:23,name:'test'}; //键名不用引号,值用单引号,在JS中,这样写都合法
alert(JSON.stringify(arr)); //但合法的JSON字符串应该是stringify后的模样 {"id":23,"name":"test"}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn