我正在用 wordpress 構建一個非常小的應用程序,需要通過 ajax 獲取 json 數據。我正面臨一個奇怪的(至少對我而言)問題。我的原始數據日志是這樣的(請注意items和children>它們是數組):object(stdClass)#6740 (2) { ["type"]=> string(5) "areas" ["items"]=> array(1) { [92]=> object(stdClass)#6742 (10) { ["term_id"]=> int(92) ["name"]=> string(6) "Italia" ["slug"]=> string(6) "italia" ["term_taxonomy_id"]=> int(92) ["taxonomy"]=> string(12) "dealer_areas" ["description"]=> string(0) "" ["parent"]=> int(82) ["count"]=> int(1) ["term_order"]=> float(0.1) ["children"]=> array(1) { [126]=> object(stdClass)#6741 (10) { ["term_id"]=> int(126) ["name"]=> string(8) "Sardegna" ["slug"]=> string(8) "sardegna" ["term_taxonomy_id"]=> int(126) ["taxonomy"]=> string(12) "dealer_areas" ["description"]=> string(0) "" ["parent"]=> int(92) ["count"]=> int(1) ["term_order"]=> float(0.10003) ["children"]=> array(0) { } } } } }}如果我將它直接傳遞給 WP_REST_Response,然后作為 json 響應 ( return new WP_REST_Response($response_obj))傳遞給 js ,我會得到這樣的日志:正如你所看到的,它不完全是 json ......有 getter/setter 方法..好的,然后我傳遞值 json 編碼 ( return new WP_REST_Response(json_encode($response_obj))) 并通過 javascript 解析JSON.parse()。我明白了:或者這個(另一個例子超過 1 個 obj)如您所見,我得到了 json,但即使原始項目數據是一個數組,現在我也得到了一個對象。如何保留原始數組類型?
如何在 json 中正確格式化 WP_REST_Response 并獲取數組而不是對象?
蠱毒傳說
2021-06-06 13:15:53