如何在php中使用\\n解码JSON

如何在php中使用\\n解码JSON,php,json,Php,Json,我有一个JSON结构,如下所示 $json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}'; 当尝试提取文本和数字时,我可以执行第一步,但嵌套的JSON有\\n,它不会将文本作为输出 PHP代码如下所示 $result = json_decode($json); print_r($result); echo "<br>"; for

我有一个JSON结构,如下所示

 $json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT 
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
当尝试提取文本和数字时,我可以执行第一步,但嵌套的JSON有
\\n
,它不会将文本作为输出

PHP代码如下所示

$result = json_decode($json);
print_r($result);
echo "<br>";
foreach($result as $key=>$value){
    echo $key.$value;
    echo "<br>";
    $result_nest = json_decode($value);
    echo  $result_nest->answerPhrase;
    echo "<br>";
$result=json\u decode($json);
打印(结果);
回声“
”; foreach($结果为$key=>$value){ echo$key.$value; 回声“
”; $result\u nest=json\u decode($value); echo$result\u nest->answerPhrase; 回声“
”;

为什么我不能在应答短语中获取文本?当文本没有
\\n

时,它可以工作。您可以尝试下面的一个。您可以用一些其他字符替换\n。如果您想在浏览器中显示enter,则可以用
替换\n。请尝试下面的代码,并让我知道它是否适用于您

<?php
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';

$result = json_decode($json);
print_r($result);
echo "\n";
foreach($result as $key=>$value){
    echo $key.$value;
    echo "<br>";
    $value = preg_replace("/\\n/", "___n___", $value);
    $result_nest = json_decode($value);
    $result_nest->answerPhrase = preg_replace("/___n___/", "\n", $result_nest->answerPhrase);

    echo  $result_nest->answerPhrase;
    echo "<br>";
}

更喜欢在解码前修复json,然后解码子json。
你们可以做循环的第二步

    function test2()
    {
        $string = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';


        $json = $this->decodeComplexJson($string);
        $number = $json->Number1;
        //Put this in a loop if you want
        $decodedNumber = $this->decodeComplexJson($number);
        var_dump($decodedNumber);
        echo $decodedNumber->answerPhrase;

    }

    function decodeComplexJson($string) { # list from www.json.org: (\b backspace, \f formfeed)
        $string = preg_replace("/[\r\n]+/", " ", $string);
        $json = utf8_encode($string);
        $json = json_decode($json);
        return $json;
    }

在尝试
json\u解码时,我得到了“控制字符错误,可能编码不正确”
该字符串我应该只替换变量中的所有\\n吗?试试这个echo“”;print\r(json\u解码($json,true));是的,这工作正常,文本显示正确。知道\\n为什么会在php中中断吗?可能json编码的值不正确。请尝试
$json='{“Number1”:“{”answerPhrase:“\nTEXT\nTEXT text text text\n”,“dateUpdatedIn毫秒”:“1234”};
$a['answerPhrase']=“\nTEXT\nTEXT text text\n”;$a['dateUpdatedIn毫秒']=“1234”;$b['Number1']=$a;$json1=json_encode($b);print__r($json1);
@Abilish Amarasekaran:请将此标记为答案我想我在其他地方看到了该代码。是否应该一直使用json解码进行此操作?不。如果json没有特殊字符,则无需执行此操作