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

Time:01-18

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

CodePudding user response:

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"
      }
    }
  }

enter image description here

CodePudding user response:

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 enter image description here

  • Related