jslt icon indicating copy to clipboard operation
jslt copied to clipboard

How to get null as a value in output from jslt

Open joel19913 opened this issue 2 years ago • 5 comments

Expected: {"data" : "test", "test" : null } Actual: {"data":"test" } When null is returned as value the entire field itself will not be returned while doing jslt transformation. Instead I need to display it as null as given in above expected result. Is it possible?

joel19913 avatar Jul 17 '23 08:07 joel19913

Interesting, this looks like a bug.

In the playground, I used this input

{
  "data" : "It's alway sunny in Philadelpia",
  "type0" : "With type"
}

.... and this transformation

{
  "data" : .data,
  "type" : fallback (.type, null)
  //"type" : if (.type) .type else (null)
}

When the tag in the input is "type0", the result is

{
  "data" : "It's alway sunny in Philadelpia"
}

When the tag is "type" though, we get:

{
  "data" : "It's alway sunny in Philadelpia",
  "type" : "With type"
}

The documentation of fallback states

Returns the first argument that has a value. That is, the first argument that is not null, [], or {}.

It would be great if the fallback also fell back on null as the last resort. How about a function fallbackWithDefault ?

Btw, using this if-condition-else-default-value trick does not work either, same result.

catull avatar Jul 19 '23 09:07 catull

Please let me know how I can achieve the expected output below.

JSLT { "outkey1":.key1, "outkey2":.key2, "outkey3":.key3, }

input { "key1": "val1", "key3": null }

actual output { "outkey1": "val1" }

expected output { "outkey1": "val1", "outkey3": null }

I tried object filter but its adding "outkey2": null which I dont want in my output

anuradharajan avatar Jul 21 '23 21:07 anuradharajan

JSLT will by default leave out object keys whose values are null. If you want to change this behaviour you need to set an object filter, as explained here.

@anuradharajan: You complain about getting "outkey2" ... well, how is JSLT supposed to know that you want outkey2, but not outkey3?

larsga avatar Jul 24 '23 15:07 larsga

key2 is not present in the input json. so thats why i dont want outkey2 in response

anuradharajan avatar Jul 24 '23 16:07 anuradharajan

Okay, that makes sense. From JSLT's point of view, however, the output you produced is:

{
"outkey1": "val1",
"outkey2": null,
"outkey3": null
}

So there's no way for JSLT to distinguish the two cases.

Of course, we have methods in JSLT for detecting whether or not a key is present, so with a language extension it would be possible to let you control the inclusion/exclusion of a key explicitly. The question is whether it's worth it.

larsga avatar Jul 25 '23 11:07 larsga