Make calculation based on string values in object in json

Hey!
I have a problem with the API from “SolarEdge”, a company that makes pv-converters.

I want to make a field in my influx bucket called “current_E_in” and one called “current_E_out” and I want to set them based on the value in an array called “connections” (see below). If that array has an object with {“from”:"GRID, “to”:“Load”}, I want to set current_E_in to the value in GRID.currentPower, if it has an object with {“from”:"Load, “to”:“GRID”}, I want to set current_E_out to the value in GRID.currentPower.

Is this possible? If yes, how?

an example JSON including said values is the following:

{
  "connections": [
    {
      "from": "GRID",
      "to": "Load"
    },
    {
      "from": "PV",
      "to": "Load"
    }
  ],
  "GRID": {
    "status": "Active",
    "currentPower": 1.59
  },
  "LOAD": {
    "status": "Active",
    "currentPower": 2.4
  },
  "PV": {
    "status": "Active",
    "currentPower": 0.81
  },
  "STORAGE": {
    "status": "Idle",
    "currentPower": 0.0,
    "chargeLevel": 1,
    "critical": false
  }
}

Hello @Marrrrrii,
You could use something like Python to do this.
You could parse the JSON.

Or if you’re looking to use telegraf
You could either use the execd processor plugin to run a python script to do that parsing/routing.
Or you could use the starlark plugin. I haven’t tested it but something like:

[[inputs.http]]
  urls = ["http://your-solaredge-api-endpoint"]  # Replace with your SolarEdge API endpoint
  method = "GET"
  headers = { "Authorization" = "Bearer YOUR_API_TOKEN" }  # Replace with your API token
  name_override = "solaredge"  # Gives the metric a consistent name
  data_format = "json"

[[processors.starlark]]
  namepass = ["solaredge"]  # Process only metrics from the "solaredge" input
  source = '''
def apply(metric):
    # Extract connections and GRID data
    connections = metric.fields.get("connections", [])
    grid = metric.fields.get("GRID", {})

    # Initialize output fields
    current_E_in = None
    current_E_out = None

    # Process connections
    for conn in connections:
        if conn.get("from") == "GRID" and conn.get("to") == "Load":
            current_E_in = grid.get("currentPower")
        elif conn.get("from") == "Load" and conn.get("to") == "GRID":
            current_E_out = grid.get("currentPower")

    # Add new fields to the metric
    if current_E_in is not None:
        metric.fields["current_E_in"] = current_E_in
    if current_E_out is not None:
        metric.fields["current_E_out"] = current_E_out

    return metric
'''
But like I said I haven't tested it. Resources for you :) 
https://www.influxdata.com/blog/how-use-starlark-telegraf/
https://github.com/influxdata/telegraf/blob/master/plugins/processors/execd/README.md

1 Like