代码之家  ›  专栏  ›  技术社区  ›  MB34

JSONLint和PHP之间的差异JSON_DECODE

  •  2
  • MB34  · 技术社区  · 14 年前

    在下面的代码中,$datastring变量中的JSON在JSONLint上作为有效的JSON传递。

    然而,我在使用PHP的json_encode时遇到语法错误。

    我能做些什么来解决这个问题?我试过去掉斜线,但还是出现了同样的错误。

    $datastring = '[{"Program": 3034370,"Column": "CLI_RID","Value": "1006278"},{"Program": 3034370,"Column": "Filename","Value": "\\\\henery\\1006278\\CONFIRMATION LETTER AVAILABLE.html"},{"Program": 3034370,"Column": "EVENT_CODE","Value": "20120725ZZAQ"},{"Program": 3034370,"Column": "DOC_NAME","Value": "Confirmation Email"},{"Program": 3034370,"Column": "PrintDate","Value": "20120410"},{"Program": 2959623,"Column": "ISSUE","Value": "Res Spring"},{"Program": 2959623,"Column": "FILENAME","Value": "~/Res/Mag.aspx?I=res_spring&P=1006278"}]';
    $data = json_decode($datastring, true);
    
    // Define the errors.
    $json_errors = array(
        JSON_ERROR_NONE => 'No error has occurred',
        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
        JSON_ERROR_SYNTAX => 'Syntax error',
    );
    
    if(!$data) {
    echo 'Last error : '. $json_errors[json_last_error()]. PHP_EOL. PHP_EOL;
    } else {
    echo print_r($data, true);
    }
    

    我将从ASP.Net页面获取这个JSON字符串。

    2 回复  |  直到 14 年前
        1
  •  3
  •   phihag    14 年前

    如果在php文本常量中写出一个字符串,则必须将所有斜杠加倍。因此,当原始JSON类似于:

    {"foo": "backslash: \\"}
    

    对应的php字符串文字为:

    $json = '{"foo": "backslash: \\\\"}';
    
        2
  •  0
  •   Ignacio Vazquez-Abrams    14 年前

    你需要 更多 反斜杠,而不是更少;PHP剥离了一个级别本身,因为您在字符串文字中使用它。