为什么php json_解码只接受整数,而不接受字符串?
经过几天的努力,终于意识到我的json语法并没有被php json_解码所接受。它似乎只在值是整数而不是字符串时才起作用。我如何使用json(如以下内容)来工作为什么php json_解码只接受整数,而不接受字符串?,php,json,Php,Json,经过几天的努力,终于意识到我的json语法并没有被php json_解码所接受。它似乎只在值是整数而不是字符串时才起作用。我如何使用json(如以下内容)来工作 <?php $json = '{"fname":2,"surname":2}'; //return No errors // $json = '{"fname": SJ011MS,"surn": something}'; //return Syntax error, malformed JSON $obj = json_deco
<?php
$json = '{"fname":2,"surname":2}'; //return No errors
// $json = '{"fname": SJ011MS,"surn": something}'; //return Syntax error, malformed JSON
$obj = json_decode($json, true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
?>
这绝对是格式错误的JSON:
$json = '{"fname": SJ011MS,"surn": something}'
您必须使用“
(甚至不是单引号”
)将字符串括起来。它实际上应该是:
$json = '{"fname": "SJ011MS","surn": "something"}'
//-----------------^-------^---------^---------^
JSON只能有基本的JavaScript类型、数组和对象
(来源:)这不是有效的JSON:
{"fname": SJ011MS,"surn": something}
属性值也需要在引号中:
{"fname": "SJ011MS","surn": "something"}
考虑一下您的示例json
{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
我已经编写了以下代码,似乎工作得很好:-
<?php
$json = '{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}';
$decodedJson = json_decode($json,TRUE);
echo $json;
print_r($decodedJson);
?>
这里要学习的是,如果JSON属性包含任何字符串,那么它应该在引号内“我真的不明白问题出在哪里;您的最终json很好,格式错误的json缺少引号。但你似乎已经知道了。这应该作为一个打字错误来结束吗?谢谢你们的帮助,伙计们,我正在绞尽脑汁去理解this@Diego你知道答案了吗?是的,我的错误是没有在字符串上使用“on string”,ruckie错了,谢谢again@Diego通过点击我的答案旁边的嘀嗒按钮来接受答案。
<?php
$json = '{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}';
$decodedJson = json_decode($json,TRUE);
echo $json;
print_r($decodedJson);
?>
{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}Array
(
[widget] => Array
(
[text] => Array
(
[data] => Click Here
[size] => 36
[style] => bold
[name] => text1
[hOffset] => 250
[vOffset] => 100
[alignment] => center
[onMouseUp] => sun1.opacity = (sun1.opacity / 100) * 90;
)
)
)