How to default a missing value in a JSON API call using JsonPath?

I am using the JSON API datasource to get power data from 3 solar panel power inverters using a stat panel with 3 fields like this:

$.Body.Data.PAC.Values.1
$.Body.Data.PAC.Values.2
$.Body.Data.PAC.Values.3

But for some reason sometimes the JSON returned by the 3 inverters only includes 2 inverters and when that happens I get a “Fields have different lengths” error and “No data” returned but ideally in that situation I want to return the data from the 2 valid fields and for the missing field default the value to something like “0” or “N/A” or “X”.

I realise this topic is not really a Grafana issue but I am hoping someone can help me.

When I use prometheus as a datasource I can use the “absent()” function for this sort of thing, and I wonder if there is a JsonPath function I can use in the fields to handle this situation? Thanks.

hey @marcusolsson any quick feedback here?

Hey @codlord,

In short, the plugin executes a JSONPath query per field. If one query returns fewer values than the other ones, it can’t know which value was actually missing. Ideally, this should be handled in the JSONPath query though unfortunately, I haven’t yet found a way to set default values with JSONPath. You might have better luck using JSONata instead, though I haven’t tried it yet myself.

For more information on the error you’re getting, check out Fields have different lengths.

Thanks for the reply. I did do some more searching and found a workaround that is good enough for my needs, instead of the 3 fields I posted above I can do a single field with a wildcard:
$.Body.Data.PAC.Values.*

Of course, if one is missing it just disappears rather than showing 0 or N/A or whatever so you can’t know which one is missing. But for my needs I just want to keep an eye on the inverters and most of the time it will show 3 values and the occasions one is missing at least it does not break the display of the other two.

2 Likes

This topic was automatically closed after 365 days. New replies are no longer allowed.