Jsonata + moment troubles

I am a bit lost with jsonata and moment.

Input data example:

[
    [1618243200000, 5.45, 5.45, 5.2, 5.2],
    [1618257600000, 4.98, 4.99, 4.96, 4.96],
    [1618272000000, 4.88, 4.88, 4.67, 4.69],
    [1618286400000, 4.74, 4.81, 4.71, 4.81]
...
]

Without the use of moment, expression:

payload.{
    "date": $[0],
    "open": $[1],
    "high": $[2],
    "low": $[3],
    "close": $[4]
}

Output:

{
    "date": 1618243200000,
    "open": 5.45,
    "high": 5.45,
    "low": 5.2,
    "close": 5.2
}

All good.

Now I am trying to format the date with moment, expression:

payload.{
    "date": $moment($[0]).format("D-MMM-YY"),
    "open": $[1],
    "high": $[2],
    "low": $[3],
    "close": $[4]
}

Output:

{
    "date": ["12-Apr-21", "1-Jan-70", "1-Jan-70", "1-Jan-70", "1-Jan-70"],
    "open": 5.45,
    "high": 5.45,
    "low": 5.2,
    "close": 5.2
}

What is happening ? Is moment evaluating/referencing differently ?

Not, as the 4 arrays has become 1 object
try

$map(payload , function($v){
    {"date": $moment($v[0]).format("D-MMM-YY"),
    "open": $v[1],
    "high": $v[2],
    "low": $v[3],
    "close": $v[4]}
})

and should return 4 objects

[{"date":"12-Apr-21","open":5.45,"high":5.45,"low":5.2,"close":5.2},
{"date":"12-Apr-21","open":4.98,"high":4.99,"low":4.96,"close":4.96},
{"date":"13-Apr-21","open":4.88,"high":4.88,"low":4.67,"close":4.69},
{"date":"13-Apr-21","open":4.74,"high":4.81,"low":4.71,"close":4.81}]

Not, as the 4 arrays has become 1 object

Well yes, I just left out the rest of the data, my bad:

I don't understand why the moment function is evaluating all elements in the array

Ah, Now i understand, I miss read your outputs. Seems to be a bug or limitation in JSONata

1 Like

Also when trying to only get the first element fails for me

"date": $moment($[0]).format("D-MMM-YY")[0],

does that not return a string?

With your map function yes. If I try it "my" way, i want to get the first element from the array, but doesnt seem to work. Your method functions properly, thanks.

I don't think it will work your way as moments is doing weird things there. If you use $fromMillis($[0],"[D]-[M]-[Y]") there expression works as it should. But there is no format for month in text format that I can see.

[edit] @bakman2 here's the answer

payload.{
    "date": [$moment($[0]).format("D-MMM-YY")][0],
    "open": $[1],
    "high": $[2],
    "low": $[3],
    "close": $[4]
}
1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.