jsonjpath

Get Values form Json, using jpath


    {
      "data": [
        {
          "id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
          "name": "abx",
          "address": {
            "address1": "New Address 1",
            "address2": "New Address 2",
            "Pin":"800001"
          }
        },
        {
          "id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
          "name": "xyz",
          "address": {
            "address1": "New Address 1",
            "address2": "New Address 2",
            "Pin":"800002"
          }
        },
        {
          "id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
          "name": "ijk",
          "address": {
            "address1": "New Address 1",
            "address2": "New Address 2",
            "Pin":"800003"
          }
        }
      ]
    }

Out put json should be like this

    [
      {
        "name": "abx",
        "Pin": "800001"
      },
      {
        "name": "xyz",
        "Pin": "800002"
      },
      {
        "name": "ijk",
        "Pin": "800003"
      }
    ]

From the input json, I want to extract all values using

jpath

Name Path = "data.name" Pin Path = "data.address.pin"

I need all values, I will create an output json.


Solution

  • If both json and jpath are dynamic then try using the below code, here i have used the same input json and output json in my code block.

       $(document).ready(function () {
            var outputArr = [];
            //Assume that these jpaths are dynamic.
            var name = "data.name", pin = "data.address.Pin";
    
            //Assigned input json object to sampleData variable.
            $.each(sampleData.data, function (item, value) {
                //Replacing 'data.' with empty('') as we are looping through data array.
                var nameValue = extractValue(value, name.replace('data.', ''));
                var pinValue = extractValue(value, pin.replace('data.', ''));
                outputArr.push({ 'name': nameValue, 'Pin': pinValue });
            });
    
            //logging into console for testing purpose.
            console.log(outputArr);
             --to do with outputArr --
    
            //Recursive function that returns the required value from the json
            function extractValue(value, jPathKey) {
                if (jPathKey.split(".").length > 1) {
                    //Here use of replace function is must as we need to get the object with the mentioned jPathKey to loop further.
                    return extractValue(value[jPathKey.replace('.', '$').split('$')[0]], jPathKey.replace('.', '$').split('$')[1])
                }
                else {
                    return value[jPathKey];
                }
            }
        });
    

    Note: Here only thing that need to take care is the case of jpath should match with case of input json