我正在尝试解析这个json '{"options":"[{\"order\":\"1\"},{\"skill\":\"\\n wajghjk \"},{\"order\":\"2\"},{\"skill\":\"\\n aswedrty \"},{\"order\":\"3\"},{\"skill\":\"\\n skill1 \"},{\"order\":\"4\"},{\"skill\":\"\\n wasedjk \"},{\"order\":\"5\"},{\"skill\":\"\\n Feldsher \"},{\"order\":\"6\"},{\"skill\":\"\\n wasedjk \"},{\"order\":\"7\"},{\"skill\":\"\\n Autotransfusionist \"},{\"order\":\"8\"},{\"skill\":\"\\n Feldsher \"},{\"order\":\"9\"},{\"skill\":\"\\n Autotransfusionist \"}]"}'
。使用代码
<?php
$json = '{"options":"[{\"order\":\"1\"},{\"skill\":\"\\n wajghjk \"},{\"order\":\"2\"},{\"skill\":\"\\n aswedrty \"},{\"order\":\"3\"},{\"skill\":\"\\n skill1 \"},{\"order\":\"4\"},{\"skill\":\"\\n wasedjk \"},{\"order\":\"5\"},{\"skill\":\"\\n Feldsher \"},{\"order\":\"6\"},{\"skill\":\"\\n wasedjk \"},{\"order\":\"7\"},{\"skill\":\"\\n Autotransfusionist \"},{\"order\":\"8\"},{\"skill\":\"\\n Feldsher \"},{\"order\":\"9\"},{\"skill\":\"\\n Autotransfusionist \"}]"}';
$decode = json_decode($json, true);
$a=array();
echo '<br/>';
foreach($decode['options'] as $a)
{
echo $a['order'];echo '<br/>';
echo $a['skill'];echo '<br/>';
}
?>
但它显示错误而无法解析。有没有更好的方法来从这个json获得秩序和技能的价值?
答案 0 :(得分:3)
那不是JSON。你正在逃避太多的双引号。
答案 1 :(得分:1)
您正在转义双引号,当字符串由单引号分隔时,它将以文字\
字符形式出现。
在json字符串上运行stripslashes,或者首先避免转义。
答案 2 :(得分:1)
json字符串有两个问题。
'{"options":"[{...}]"}'
。你用引号括起了javascript [array],把它变成了一个字符串。正确的json应如下所示:
{"options":[{"order":"1"},{"skill":"\\n wajghjk "},{"order":"2"},{"skill":"\\n aswedrty "},{"order":"3"},{"skill":"\\n skill1 "},{"order":"4"},{"skill":"\\n wasedjk "},{"order":"5"},{"skill":"\\n Feldsher "},{"order":"6"},{"skill":"\\n wasedjk "},{"order":"7"},{"skill":"\\n Autotransfusionist "},{"order":"8"},{"skill":"\\n Feldsher "},{"order":"9"},{"skill":"\\n Autotransfusionist "}]}
答案 3 :(得分:1)
显示错误,无法解析。
PHP在调试json方面相当薄弱。你所能做的只是
$json_errors = array(
"",
"The maximum stack depth has been exceeded",
"Invalid or malformed JSON",
"Control character error, possibly incorrectly encoded",
"Syntax error",
"Malformed UTF-8 characters, possibly incorrectly encoded",
);
$decode = json_decode($json, true);
if ($error = json_last_error())
{
trigger_error($json_errors[$error]);
}
但是,为了获得值,你必须有一个有效的json字符串,而不是任意字符串由一些引号和斜杠组成。
当然你应该永远不会手动创建一个json字符串。