0
    {
      "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"
          }
        }
      ]
    }

输出的 json 应该是这样的

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

从输入 json 中,我想使用提取所有值

路径

名称路径 = “data.name” 引脚路径 = “data.address.pin”

我需要所有值,我将创建一个输出 json。

4

1 回答 1

0

如果两者json都是jpath动态的,那么尝试使用下面的代码,这里我在我的代码块中使用了相同的输入 json 和输出 json。

   $(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];
            }
        }
    });

注意:这里唯一需要注意的是大小写jpath应该与输入的大小写匹配json

于 2020-04-11T17:29:17.507 回答