JSONPATH transformation for optional element



I am using HTTP binding to receive JSON formatted data and using JSONPATH transformation in my channel definition as state transformation.
That’s all working fine with one exception:

In the JSON response there is an optional element; in some responses the element is included and in some it is missing.
If the element is included, the transformation is working fine and any linked item is updated accordingly.
However if the element is missing in the response, I see an error message in the log and the item is not updated.

My aim is, that in case the optional element is missing within the JSON, that the item is still updated with an empty value, as otherwise the item would have an outdated state.

Question: Is this possible at all with JSONPATH transformation or is there another way you can recommend to handle optional elements within JSON data.

Thanks in advance,

This precludes the usual “filter with REGEX” method, because that simply ignores ‘missing’ input.

The easiest way is probably to write a little JS transformation, that does its own JSON analysis and returns either ‘the value’ or UNDEF for your ‘empty’.

1 Like

already thought about the same, but had the hope that there is a better idea

Followup question on how JSONPATH and JS transformation will work together:

My initial json is well formatted:
{ "year": "2022", "month": "1", "day": "20", "weekday": "5", "hour": "16", "minute": "56" }

but when I first apply JSONPATH transformation on the channel and link a string item to the output than the item is as following:

{year=2022, month=1, day=20, weekday=5, hour=16, minute=56}

The JSONPATH will remove quotes and replace : by =

If I now apply an additional JS transformation as a profile on the channel link with a JSON.parse function, it will fail because the JSON string is not correct formatted anymore.

E.g. that simple test JS transformation is not working because of the wrong format:

(function(i) {
	var obj = JSON.parse(i);
	return obj.year;

I don’t know what you are doing with JSONPATH, you’ve not shown us. If the element is missing, it will blow up, which is what you are trying to avoid.
Do the whole business in one JS transform without using JSONPATH.

I have a 24.000 character JSON string and I wanted to only pass the relevant part of the JSON to the JS transformation; therefore I wanted to combine JSON & JS transformation.
But will try your advice and only do JS.

One of them has to deal with the whole string.

If the JSONPATH could be persuaded to do something sensible with a missing element in order to pass along to javascript afterwards, then you wouldn’t need the javascript at all …