使用转义斜杠时出现JSON语法错误

时间:2022-05-10 15:38:30

TOTALLY RE-EDITED QUESTION

完全重新编辑的问题

<?php
   $s1 = '{"req":"auth","token":"1234567\/\\"}'; // this seems to be valid, isn't it?
   $s2 = '{"req":"auth","token":"123456\/\\7"}'; // this seems to be valid, isn't it?
   $s3 = '{"req":"auth","token":"123456789"}';

   print_r(json_decode($s1,true));
   echo " - ERRORCODE FOR CASE#1 IS:" . json_last_error() . '<br />';

   print_r(json_decode($s2,true));
   echo " - ERRORCODE FOR CASE#2 IS:" . json_last_error() . '<br />';

   print_r(json_decode($s3,true));
   echo " - ERRORCODE FOR CASE#3 IS:" . json_last_error() . '<br />';
?>

RESULTS:

 - ERRORCODE FOR CASE#1 IS:4
 - ERRORCODE FOR CASE#2 IS:4
Array ( [req] => auth [token] => 123456789 ) - ERRORCODE FOR CASE#3 IS:0

QUESTION:

Why s1 and s2 do not work, and how to fix this?

为什么s1和s2不起作用,以及如何解决这个问题?

2 个解决方案

#1


1  

I'm going to guess you're testing stuff here, therefore having:

我猜你在这里测试的东西,因此有:

$test_json = '{"req":"auth","token":"1234567\/\\"}';

While single quotes do ignore things like \n, \\ is still treated as a single backslash. This means your resulting JSON is:

虽然单引号确实忽略了\ n之类的内容,但仍然将\\视为单个反斜杠。这意味着您生成的JSON是:

{"red":"auth","token":"1234567\/\"}

Which, needless to say, is a syntax error.

不用说,这是语法错误。

If you're getting your JSON from an outside source, you won't need to worry about this, but if you're testing with a hardcoded JSON string, you'll need:

如果您从外部源获取JSON,则无需担心这一点,但如果您使用硬编码的JSON字符串进行测试,则需要:

$test_json = '{"req":"auth","token":"1234567\/\\\\"}';

#2


0  

You have to call stripslashes function before the json_decode, i.e. add below 2 lines before your first print_r so that it decodes and prints correct array.

您必须在json_decode之前调用stripslashes函数,即在第一个print_r之前添加2行以下,以便它解码并打印正确的数组。

$s1 = stripslashes($s1);
$s2 = stripslashes($s2);

#1


1  

I'm going to guess you're testing stuff here, therefore having:

我猜你在这里测试的东西,因此有:

$test_json = '{"req":"auth","token":"1234567\/\\"}';

While single quotes do ignore things like \n, \\ is still treated as a single backslash. This means your resulting JSON is:

虽然单引号确实忽略了\ n之类的内容,但仍然将\\视为单个反斜杠。这意味着您生成的JSON是:

{"red":"auth","token":"1234567\/\"}

Which, needless to say, is a syntax error.

不用说,这是语法错误。

If you're getting your JSON from an outside source, you won't need to worry about this, but if you're testing with a hardcoded JSON string, you'll need:

如果您从外部源获取JSON,则无需担心这一点,但如果您使用硬编码的JSON字符串进行测试,则需要:

$test_json = '{"req":"auth","token":"1234567\/\\\\"}';

#2


0  

You have to call stripslashes function before the json_decode, i.e. add below 2 lines before your first print_r so that it decodes and prints correct array.

您必须在json_decode之前调用stripslashes函数,即在第一个print_r之前添加2行以下,以便它解码并打印正确的数组。

$s1 = stripslashes($s1);
$s2 = stripslashes($s2);