[SOLVED] Help needed with transforming json into numbers for manipulation

wondering if someone could help me with what should just be simple. i have a ‘string item’ containing json data like this:

{“contact”:true,“linkquality”:47,“battery”:91,“voltage”:2985}

String door_sensor_01_json "JSON String" {channel="mqtt:topic:door_sensor_01:json"}

so then i have a rule that splits out the json into individual ‘number’ items:

rule "Convert JSON to individual values"
  when
    Item door_sensor_01_json changed
 then
    // use the transformation service to retrieve the value
    val battery = transform("JSONPATH", "$.battery", door_sensor_01_json.state.toString)
    val linkquality = transform("JSONPATH", "$.linkquality", door_sensor_01_json.state.toString)
    val voltage = transform("JSONPATH", "$.voltage", door_sensor_01_json.state.toString)
    val contact = transform("JSONPATH", "$.contact", door_sensor_01_json.state.toString)
    // post the new value to the Number Item
    door_sensor_01_battery.postUpdate( battery )
    door_sensor_01_linkquality.postUpdate( linkquality )
    door_sensor_01_voltage.postUpdate( voltage )
    // door_sensor_01_contact.postUpdate( contact )
 end

this all works and the items get the values.

Now what i would like is to be able to divide the ‘voltage’ by 1000 before doing the postUpdate - and this is where i’m failing miserably!
i’ve tried various combinations of things but just keep getting errors in the log. i’m thinking that ‘voltage’ is a string that i need to convert first before doing maths on it? - but then why does it postUpdate to a ‘Number’ item?

can anyone give me any pointers please?

Yes. Float::parseFloat(somestring) should be useful

postUpdate accepts a string and does it own parsing,if it can.
someItem.postUpdate("3.142") works.

that works a treat now. thanks so much for your help!

for completeness, i updated the rule to look like this:

rule "Convert JSON to individual values"
  when
    Item door_sensor_01_json changed
 then
    // use the transformation service to retrieve the value
    val battery = transform("JSONPATH", "$.battery", door_sensor_01_json.state.toString)
    val linkquality = transform("JSONPATH", "$.linkquality", door_sensor_01_json.state.toString)
    val voltage = transform("JSONPATH", "$.voltage", door_sensor_01_json.state.toString)
    val contact = transform("JSONPATH", "$.contact", door_sensor_01_json.state.toString)
    // post the new value to the Number Item
    var voltagenew = Float::parseFloat(voltage)
    var voltagenew2 = voltagenew/1000
    door_sensor_01_battery.postUpdate( battery )
    door_sensor_01_linkquality.postUpdate( linkquality )
    door_sensor_01_voltage.postUpdate( voltagenew2 )
    // door_sensor_01_contact.postUpdate( contact )
 end

1 Like

Please tick the solution post.
Thanks

1 Like