简体   繁体   中英

Pull elements out of two arrays to make a "flat" item list

I need to merge array data from two different arrays from the Input JSON and make a flat list of items in the Output JSON. The first array contains the key required for the output and the second array contains the value.

So far, all my attempts at a spec haven't even come close, which is why I haven't listed one. Please see the Input and Desired Output below. Thanks for any help!!

Input JSON:

{
  "data": [
    {
      "2": {
        "value": "DC1"
      },
      "3": {
        "value": 5
      }
    },
    {
      "2": {
        "value": "DC2"
      },
      "3": {
        "value": 10
      }
    }
  ],
  "fields": [
    {
      "id": 2,
      "label": "DataCenter",
      "type": "text"
    },
    {
      "id": 3,
      "label": "CCount",
      "type": "numeric"
    }
  ],
  "metadata": {
    "numFields": 2,
    "numRecords": 2,
    "skip": 0,
    "totalRecords": 2
  }
}

Desired Output JSON:

[
  {
    "DataCenter": "DC1",
    "CCount": "5"
  },
  {
    "DataCenter": "DC2",
    "CCount": "10"
  }
]

You can use this spec:

[
  {
    "operation": "shift",
    "spec": {
      "data": "&",
      "fields": {
        "*": {
          "label": "fields.@(1,id)"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "*": {
            "*": "[&2].@(4,fields.&1)"
          }
        }
      }
    }
  }
]

In your desired output CCount value is a string, You can add the below spec to change an integer to a string.

,
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "CCount": "=toString"
      }
    }
  }

在此处输入图像描述

You might reciprocally match id value of fields array vs. the object keys of the data array within a common object within the first shift transformation spec in order to prepare for the second one in which we tile the attributes into their individual objects such as

[
  {
    "operation": "shift",
    "spec": {
      "*": { // represents the node for both "data" and "fields" arrays
        "*": {
          "*": {
            "value": "&1.&",
            "@1,label": "@2,id.&"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "value": {
          "*": "[&].@2,label"
        }
      }
    }
  }
]

the demo on the site http://jolt-demo.appspot.com/ is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM