I have a JSON similar to:
{
"orders":{
"678238": {
"orderId": 678238,
"itemName": "Keyboard"
},
"8723423": {
"orderId": 8723423,
"itemName": "Flash Drive"
}
}
}
I am trying JSON path to get first orderId. When I try $..orderId I get an array listing both orderId, then I tried $..[0].orderId to get first item from that array (following JsonPath - Filter Array and get only the first element). But it does not work. I am confused.
CodePudding user response:
try this
console.log(jsonPath(json,"$['orders'].[orderId]")[0]); //678238
CodePudding user response:
You're almost there. You need to combine the two things you've done.
$..orderId[0]
The ..orderId
recursively searches for orderId
properties, giving you all of their values, as you mentioned. Taking that result, you just need to apply the [0]
.
Be careful, though. Because your data is an object, keys are unordered, so the first one in the JSON text may not be the first one encountered in memory. You'll want to do some testing to confirm your results are consistent with your expectations.