-2

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.

MAK
  • 1
  • 1

3 Answers3

1

try this

console.log(jsonPath(json,"$['orders'].[orderId]")[0]); //678238
Serge
  • 40,935
  • 4
  • 18
  • 45
  • I am looking for a JSON path; as my application cannot run JSONPath to get array and then lookup 0th item. – MAK Jun 28 '22 at 13:03
  • 1
    @MAK remove jsonpath tag then and point the language are you using. Json path always returns an array so you will always need 0th. – Serge Jun 28 '22 at 13:25
  • sure, but I want the reference to 0th item within JSONPath – MAK Jun 29 '22 at 18:03
  • 1
    @MAK if your json is array you can do it . Path is designed for arrays – Serge Jun 29 '22 at 19:59
0

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.

gregsdennis
  • 7,218
  • 3
  • 38
  • 71
0

Your JSON doesn't even have an array and you are expecting to get first item from the array which is why it's not working.

Suppose, if the structure of JSON is modified like this

{
    "orders": [{
            "orderId": 678238,
            "itemName": "Keyboard"
        },
        {
            "orderId": 8723423,
            "itemName": "Flash Drive"
        }
    ]
}

then you can use the query to get the first order.

$.orders[0].orderId
Akshay G
  • 2,070
  • 1
  • 15
  • 33
  • I cannot modify the JSON structure. I have to use JSONPath to get the number 678238 as an output. – MAK Jun 29 '22 at 18:01
  • I know you cannot modify, but included the answer to demonstrate what’s different in your question and the the other post which has answer to clear any confusion – Akshay G Jun 30 '22 at 16:15
  • @MAK Can you at least do it in two steps? 1. `$.orders.*` --- will give you array as output 2. `$[0].orderId` -- Fetch 0th item from the output of the first query – Akshay G Jul 03 '22 at 11:34