Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a single array item from JSON in PHP (NODE.JS and EXPRESS API)

I have Express running on a custom node API that breaks down a large JSON into bite sized chunks for mobile usage.

One of the section goes through a mass of items and returns only one of them. However the returned data is still wrapped in [ .. ] which makes working with it tough.

My NODE.JS code snippet that deals with my routed request

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);
});

so if you access the url

http://(domain)3000/ppm/summary/operators/25

the following data is returned

[
  {
    "code": "25",
    "keySymbol": "",
    "name": "First Great Western",
    "Total": "577",
    "PPM": {
      "rag": "G",
      "text": "94"
    },
    "RollingPPM": {
      "trendInd": "+",
      "displayFlag": "Y",
      "rag": "G",
      "text": "97"
    }
  }
]

How can I break that object out of the [ .. ] so it is not returned as an array object and only shows as

 {
    "code": "25",
    "keySymbol": "",
    "name": "First Great Western",
    "Total": "577",
    "PPM": {
      "rag": "G",
      "text": "94"
    },
    "RollingPPM": {
      "trendInd": "+",
      "displayFlag": "Y",
      "rag": "G",
      "text": "97"
    }
  }

Alternativly, how can I work with the [ .. ] object in PHP? When I am trying to echo it using

$operatorJSON=file_get_contents("operator.json");
$operator=json_decode($operatorJSON);

echo $operator->PPM->text;

It errors if the JSON has the [ ]

I suspect it is being treated as an array object

UPDATE : I tried to flatten the array

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));
});

but the object returned is still in [ ]

like image 422
MOLEDesign Avatar asked Aug 30 '26 10:08

MOLEDesign


1 Answers

If i understand correctly , i think the most easy way is use the index to get the element in array

res.json(with_operatorCode[0]);
like image 84
qianjiahao Avatar answered Sep 02 '26 04:09

qianjiahao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!