我有一个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>";
为什么我不能用短语中的文字?它在文本没有\\n
答案 0 :(得分:0)
您可以尝试以下方法。您可以将\ n替换为其他一些字符。如果要在浏览器中显示输入,则可以用\替换\ 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>";
}
答案 1 :(得分:0)
喜欢在解码之前修复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;
}