为什么php json_decode只接受整数,而不是字符串?

时间:2017-11-24 13:30:48

标签: php json

点击我的已经几天,终于意识到我的json语法不被php json_decode接受。它似乎仅在值是整数而不是字符串时才起作用。我如何设法使用如下的json工作?

<?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,例如:

{"widget": {
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}} 

2 个答案:

答案 0 :(得分:0)

这不是有效的JSON:

{"fname": SJ011MS,"surn": something}

属性值也必须在引号中:

{"fname": "SJ011MS","surn": "something"}

答案 1 :(得分:0)

考虑你的例子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);
?>

<强>输出:

{"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;
                )

        )

)

这里的要学习的东西是,如果JSON属性包含任何字符串,那么它应该在&#34;引号&#34; 中。