json_decode returns string type instead of object

后端 未结 3 2042
情歌与酒
情歌与酒 2021-01-02 10:49

I\'m passing a JSON-encoded string to json_decode() and am expecting its output to be an object type, but am getting a string type instead. How can I return an

相关标签:
3条回答
  • 2021-01-02 11:09

    The function json_encode is used to encode a native PHP object or array in JSON format.

    For example, $json = json_encode($arr) where $arr is

    $arr = array(
      'a' => 1,
      'b' => 2,
      'c' => 3,
      'd' => 4,
      'e' => 5,
    );
    

    would return the string $json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'. At this point, you do not need to encode it again with json_encode!

    To obtain your array back, simply do json_decode($json, true).

    If you omit the true from the call to json_decode you'll obtain an instance of stdClass instead, with the various properties specified in the JSON string.

    For more references, see:

    http://www.php.net/manual/en/function.json-encode.php

    http://www.php.net/manual/en/function.json-decode.php

    0 讨论(0)
  • 2021-01-02 11:22

    Instead of writing on the JSON array, try putting it into a PHP array first.

    <?php
    $array = array(
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4,
    'e' => 5
    );
    //Then json_encode()
    $json = json_encode($array);
    echo $json;
    die;
    ?>
    

    In you case, you are using ajax. So when you get a success, you can do this:

    $.ajax({
        url: 'example.com',
        data: {
    
        },
        success: function(data) {
            console.log(data);
        }
    });
    

    Where after data inside console.log() can add the json var like data.a, data.b...

    Also, with the string you providedm you do not need to json_encode since it is alrady in json format

    0 讨论(0)
  • 2021-01-02 11:30
    var_dump(json_decode($json, true));
    

    http://hk.php.net/manual/en/function.json-decode.php

    0 讨论(0)
提交回复
热议问题