-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.

3 Answers 3

1

try this

console.log(jsonPath(json,"$['orders'].[orderId]")[0]); //678238
Sign up to request clarification or add additional context in comments.

4 Comments

I am looking for a JSON path; as my application cannot run JSONPath to get array and then lookup 0th item.
@MAK remove jsonpath tag then and point the language are you using. Json path always returns an array so you will always need 0th.
sure, but I want the reference to 0th item within JSONPath
@MAK if your json is array you can do it . Path is designed for arrays
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.

1 Comment

I have tried this already, this does not work either
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

3 Comments

I cannot modify the JSON structure. I have to use JSONPath to get the number 678238 as an output.
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
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.