cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Combining all records in one single JSON

KTsnap
New Contributor III

Hi Team,
I have below input

[
  {
    "parents": "A",
    "value": "1"
  },
  {
    "parents": "B",
    "value": "2"
  },
  {
    "parents": "C",
    "value": "3"
  },
  {
    "parents": "D",
    "value": "4"
  }
]

When i tried using the expression :
{}.extend({โ€œcontrollingFieldValueโ€:[$parents],โ€œvalueNameโ€:$value})

I got the below Output

[
  {
    "controllingFieldValue": [
      "A"
    ],
    "valueName": "1"
  },
  {
    "controllingFieldValue": [
      "B"
    ],
    "valueName": "2"
  },
  {
    "controllingFieldValue": [
      "C"
    ],
    "valueName": "3"
  },
  {
    "controllingFieldValue": [
      "D"
    ],
    "valueName": "4"
  }
]

But i am expecting the above output to be in one JSON.Can experts please guide.

4 REPLIES 4

bojanvelevski
Valued Contributor

Hi @KTsnap,

Donโ€™t know what you mean by โ€œJSONโ€ output? If you are referring to the Array value of โ€œcontrollingFieldValueโ€, than just remove the square brackets from your expression

KTsnap
New Contributor III

Hi Bojan,
IN this way ,

[
"Value" : {
  {
    "controllingFieldValue": [
      "A"
    ],
    "valueName": "1"
  },
  {
    "controllingFieldValue": [
      "B"
    ],
    "valueName": "2"
  },
  {
    "controllingFieldValue": [
      "C"
    ],
    "valueName": "3"
  },
  {
    "controllingFieldValue": [
      "D"
    ],
    "valueName": "4"
  }
}
]

This is not a valid JSON. The value of the โ€œValueโ€ object can either be a string,number,boolean, array , or object with key value pairs, but not multiple object literals. You can group all of the documents in one array ($group) , and use the following expression:

$group.map(x=>{"controllingFieldValue":[x.parents],"valueName":x.value})

And map the target path as Value, than youโ€™ll have all of the objects but in an array.

KTsnap
New Contributor III

This helpedโ€ฆ Thank you ๐Ÿ™‚