Thursday, February 15, 2018

JSONata - Application Notes - Part 1



JSONata capabilities can be used in two Node-RED nodes: Change and Switch.

Advantages of using JSONata:

  • its use is optional 
  • can easy the development of Node-RED flows
  • results in less use of code in function nodes
  • it is really powerful to handle JSON structures
  • has a nice and helpful web application named "JSONata Exerciser" to test expressions


Disadvantages of using JSONata

  • need to learn a specific sintax
  • makes hard for someone to understand a Node-RED flow if this person is not acquainted with JSONata



Example 1 - Doing a calculation





Example 2- Transform a given JSON data set to a new structure


Original Data set:

{
  "payload": [
    {
      "description": "Text 1",
      "id": "001"
    },
    {
      "description": "Text 2",
      "id": "002"
    },
    {
      "description": "Text 3",
      "id": "003"
    },
    {
      "description": "Text 4",
      "id": "004"
    }
  ]
}


JSONata expression

payload.{description:id}


Transformed data set:

[{
"Text 1": "001"
},
{
"Text 2": "002"
},
{
"Text 3": "003"
},
{
"Text 4": "004"
}
]


JSONata expression

payload{description:id}



Transformed data set:


{
"Text 1": "001",
"Text 2": "002",
"Text 3": "003",
"Text 4": "004"
}



JSONata expression

payload.[id, description]


Transformed data set:

[
[
"001",
"Text 1"
],
[
"002",
"Text 2"
],
[
"003",
"Text 3"
],
[
"004",
"Text 4"
]
]



Example 3- Transform a given JSON data set to a new structure

Original Data set:

[{
"series": [
""
],
"data": [
[
16.8192,
18.8832,
11.2728,
9.614400000000002
]
],
"labels": [
"sáb. 30 dic.",
"dom. 31 dic.",
"lun. 01 ene.",
"mié. 03 ene."
]
}]



JSONata expression, using the map function

$map(data, function($v, $i, $a) {

   {"date":labels[$i],"value":$v}

})


Resulting structure:

[

{

"date": "sáb. 30 dic.",
"value": 16.8192

},

{

"date": "dom. 31 dic.",
"value": 18.8832

},

{

"date": "lun. 01 ene.",
"value": 11.2728

},

{

"date": "mié. 03 ene.",
"value": 9.6144

}

]


No comments: