我正在wordpress中构建一个非常小的应用程序,需要通过ajax获取json数据。我面临一个奇怪的问题(至少对我来说)。我的原始数据日志是这样的(请注意项目和子项>它们是数组):
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))
)并通过JSON.parse()
在javascript中进行解析。我明白了:
或这个(另一个示例,对象超过1个)
如您所见,我得到了json,但是即使原始项目数据是一个数组,现在我也得到了一个对象。如何保留原始数组类型?
答案 0 :(得分:0)
我自己的答案是:
简而言之:由于javascript需要连续的整数键,因此无法将php非连续索引数组转换为javascript数组。在所有其他情况下,javascript都读为关联数组或对象(本质上是相同的)。因此,php非连续索引数组的json转换将始终输出对象。