php上的递归JSON解码

时间:2015-08-13 11:26:44

标签: php json recursion escaping double-quotes

我有一个数据保存在sql上,当我将它导入到php并尝试解码为一个对象时,我发现一个小问题,因为主对象中有很多对象。我的数据是:

[{
    "other":"{
        \"father\":\"[\"father-3\",\"undefined\",\"father-class\"]\",
        \"element\":\"[\"element-3\",\"height: 265px;\",\"element-class\"]\"
    }",
    "type":"login",
    "columns":4,
    "offsets":0,
    "order":"father,facebook,twitter,email",
    "father":"{login-title}"
},
{
    "other":"{
        \"text\":\"[\"text-4\",\"\",\"text-class\"]\",
        \"element\":\"[\"element-4\",\"height: 265px;\",\"element-class\"]\"
    }",
    "type":"text",
    "columns":4,
    "offsets":2,
    "order":"text",
    "text":"<p>hola <strong>muchachos </strong>como est&aacute;is?</p>"
}]

“其他”是该数组的每个对象内的对象。当我为数组创建一个json_decode时,我得到的数组没有问题,但如果我尝试获取另一个对象,我会得到NULL。最后我找到了一个解决方案,但我不确定它是否是最好的(这就是我提问的原因):

$elements = json_decode($value);
foreach($elements as $element)
{
    echo "<h1>ELEMENTO</h1>";
    var_dump($element);
    echo "<h1>ORIGINAL OTHER</h1>";
    echo "<textarea>".$element->other."</textarea>";
    $element->other = str_replace("\"]", "\\\"]",$element->other);
    $element->other = str_replace("[\"", "[\\\"",$element->other);
    $element->other = str_replace("\",\"", "\\\",\\\"",$element->other);
    $element->other = str_replace("]\\\",\\\"", "]\",\"",$element->other);
    $other = json_decode($element->other);
    echo "<h1>OTHER</h1>";
    echo "<textarea>".$element->other."</textarea>";
    var_dump($other);
}

$ value是数据库中的原始数据 我认为发生的问题是,在ORIGINAL OTHER中,显示的文字没有双引号的scape反斜杠 - &gt; “而我所看到的是:

{
    "father":"["father-3","undefined","father-class"]",
    "element":"["element-3","height: 265px;","element-class"]"
}

由于这个原因,我需要制作所有这些我不喜欢的str_replace,我认为必须采用另一种方式来实现它。
我正在观察解码函数存在 $ depth 限制,我认为它是用于解码递归对象,但我不确定它是如何工作的。

谢谢。

1 个答案:

答案 0 :(得分:0)

你应该在打开和关闭嵌套对象/数组的大括号和括号时删除双引号

"other":{
    \"father\":[\"father-3\",\"undefined\",\"father-class\"],
    \"element\":[\"element-3\",\"height: 265px;\",\"element-class\"]
},

它应解码好,希望它有帮助