我让Express运行在自定义节点API上,该API将大型JSON分解为一口大小的块供移动使用.
部分中的一个遍历大量项目,仅返回其中一项.但是,返回的数据仍包装在[..]中,这使得处理它变得困难.
我的NODE.JS代码段处理了我的路由请求
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
res.json(with_operatorCode);
});
因此,如果您访问网址
http://(domain)3000/ppm/summary/operators/25
返回以下数据
[
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendind": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
]
我该如何将该对象从[..]中分解出来,使其不作为数组对象返回,而仅显示为
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendind": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
或者,如何使用PHP中的[..]对象?当我尝试使用时回显它
$operatorjson=file_get_contents("operator.json");
$operator=json_decode($operatorjson);
echo $operator->PPM->text;
如果JSON具有[],则会出错
我怀疑它被视为数组对象
更新:我试图展平数组
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
var obj = arr.reduce(function(x, y, i) {
x[i] = y;
return x;
}, {});
res.json(obj(with_operatorCode));
});
但是返回的对象仍然在[]中
解决方法:
如果我理解正确,我认为最简单的方法是使用索引来获取数组中的元素
res.json(with_operatorCode[0]);