【发布时间】:2014-10-01 21:10:51
【问题描述】:
我从后端收到 API 响应,并希望通过 JS 将其转发给客户端(浏览器)。 但不应该有来自服务器的空洞响应。
一个 JSON 可能如下所示:
"{\"total\":6,\"sort\":{\"field\":\"created_at\",\"order\":\"desc\"},\"constraints\": [],\"pagination\": {\"current\":1,\"previous\":null,\"next\":null,\"per_page\":25,\"pages\":1,\"count\":6},\"response\":[{\"id\":10,\"name\":\"Prof. Dr. Dr. h. c.\",\"people_count\":2,\"allowed_actions\":{\"destroy\":false}},{\"id\":9,\"name\":\"Dr. h. c.\",\"people_count\":1,\"allowed_actions\":{\"destroy\":false}},{\"id\":8,\"name\":\"Dr. Dr.\",\"people_count\":0,\"allowed_actions\":{\"destroy\":true}},{\"id\":7,\"name\":\"Prof. Dr.\",\"people_count\":0,\"allowed_actions\":{\"destroy\":true}},{\"id\":6,\"name\":\"Prof.\",\"people_count\":4,\"allowed_actions\":{\"destroy\":false}},{\"id\":5,\"name\":\"Dr.\",\"people_count\":110,\"allowed_actions\":{\"destroy\":false}}],\"statuscode\":200}"
为了过滤它,我开始编写白名单。他以数组(“statuscode”,“response.name”,“response.id”,“total”)的形式获取洞json + 白名单。 现在他应该遍历这个 JSON 递归并返回一个具有相同结构但删除了所有其他节点的 json。
这是我目前的状态:
public function filter($response,$whitelist,$depth = 0) {
$filteredResponse = "";
foreach (json_decode($response,true) as $key => $value) {
foreach ($whitelist as $item) {
$items = explode(".",$item);
foreach($items as $it) {
if($it === $key && strlen($it)>0) {
if(is_array($value)) {
for($i=1;$i<count($items);$i++) {
$str .= $it.".";
}
$filteredResponse[$it] = $this->filter(json_encode($value),array($str),$depth+1);
}
else $filteredResponse[$key] = $value;
}
}
}
}
return json_encode($filteredResponse);
}
我现在的结果是{"total":6,"response":"\"\"","statuscode":200}。 任何人都可以帮助我吗?
【问题讨论】:
-
你的 JSON 是一个包含更多 JSON 的字符串?
-
我得到了一个如上所示的字符串。使用 json_decode() 和 json_encode 我正在获取我的 json 或返回字符串。
-
@ÁlvaroG.Vicario 没有它的常规 json(Firefox 可以很好地解析它)
-
我建议编写一个过滤器函数,该函数已经采用解码数组,并将结果重新编码为 json - 这样它只关心 php-array 而不是 JSON
-
@birdspider - 问题中显示的内容没有通过JSONLint,这就是我要问的原因。虽然它可能与问题无关:我认为这完全是关于如何循环深度嵌套的数组,而不是 JSON。