json_decode(json_encode(一个索引数组))给出NULL [英] json_decode(json_encode(an indexed array)) gives NULL

查看:227
本文介绍了json_decode(json_encode(一个索引数组))给出NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用json_encode对用户输入的测试区内容进行编码 这是它在mysql中的存储方式("aaa"之后返回到一行)

i encode the user entred testarea content with json_encode here is how it storred in mysql (there is a return to line after "aaa")

{"content":"aaa
bbb"}

现在,当我从数据库中获取内容并尝试使用json_decode对其进行解码时,我为此得到NULL,而不是预期的结果.

now when i get the the content from database and trying to decoded it using json_decode, i get NULL for this, instead of what expected.

出了什么问题? PHP中的错误?

what wrrong? a bug in PHP?

更多详细信息

$data =array('content'=>$textareaText);
$addres_insert = "INSERT INTO `rtable` (`data`) VALUES ('".json_encode($data)."');";
$rows = mysql_query($addres_insert);

然后获取内容

$query = "SELECT * FROM  `rtable` WHERE id =  '".$id."'";
        $rows = mysql_query($query);
    if ( $rows ){
        $row = mysql_fetch_array($rows);
        $res['data'] = json_decode($row['data']);//i tryed substr($row['data'],3) but didn't work
    }

推荐答案

JavaScript和JSON不允许在字符串中包含换行符.您需要逃脱它们.

JavaScript and JSON do not allow line returns to be contained within a string. You need to escape them.

json_encode()应该为您自动转义.

这是我在PHP交互式shell上使用您的JSON代码进行播放的结果:

Here is the output of my playing with your JSON code supplied on the PHP interactive shell:

php > $json = '{"content":"aaa
php ' bbb"}';
php > var_dump(json_decode($json, true));
NULL

如您所见,当我退出行时,它可以正常工作:

As you can see when I escape your line return it works just fine:

php > $json = '{"content":"aaa\n bbb"}';
php > var_dump(json_decode($json, true));
array(1) {
  ["content"]=>
  string(8) "aaa
 bbb"
}

在与类似问题有关的先前问题中也对此进行了进一步讨论:

This is also further discussed in a previous question relating to a similar problem: Problem when retrieving text in JSON format containing line breaks with jQuery

这篇关于json_decode(json_encode(一个索引数组))给出NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆