Search code examples
javascriptjsonjmespath

Extract nested element value from JSON object using JMESPath


I am trying to extract and transform elements from a JSON document using JMESPath. Here is my test JSON array:

const search = jmespath.search;
const testData =
{
"ServiceAccount": [
    {
        "Type": "WIDGET",
        "ID": [
            {
                "OrderNum": "12345",
                "OrderTyp": "ABDCD"
            }
        ]
      }
    ]
};

I am trying to extract the value of the OrderNum key using the following JMESPath expression, but it returns null. Here is my search expression:

const result = search(testData, 'ServiceAccount.ID.OrderNum');
console.log(result);

Why is this not working?


Solution

  • const testData =
    {
    "ServiceAccount": [
        {
            "Type": "WIDGET",
            "ID": [
                {
                    "OrderNum": "12345",
                    "OrderTyp": "ABDCD"
                }
            ]
          }
        ]
    };
    
    const result = jmespath.search(testData, 'ServiceAccount[].ID[].OrderNum');
    console.log(result);