[英]How to parse json in 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 \\"}]"}'
。 使用代碼
<?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獲取命令和技能的值?
那不是JSON。 您正在轉義過多雙引號。
您正在轉義雙引號,當字符串由單引號分隔時,雙引號將以文字\\
字符形式出現。
要么在json字符串上運行反斜杠 ,要么首先避免轉義。
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 "}]}
它顯示錯誤並且無法解析。
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字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.