json_decode() returns null issues

前端 未结 10 2171
误落风尘
误落风尘 2020-12-03 11:47

I\'ve an issue with my JSON. It works returns correctly in PHP 5.3 (so I can\'t use json_last_error()), and it returns successfully when I copy string explicitly into json_d

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 12:33

    Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.

    Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error() function to determine the error it will return integer but here are those int described:

    0 = JSON_ERROR_NONE

    1 = JSON_ERROR_DEPTH

    2 = JSON_ERROR_STATE_MISMATCH

    3 = JSON_ERROR_CTRL_CHAR

    4 = JSON_ERROR_SYNTAX

    5 = JSON_ERROR_UTF8

    In my case I got output of json_last_error() as number 4 so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:

    '\'title\' error ...'
    

    After that is really just an easy fix.

    $json = json_decode(stripslashes($response));
    if (json_last_error() == 0) { // you've got an object in $json}
    

提交回复
热议问题