Cannot Update Number item from JSON due text into value

I have an item with iside some json.
Some value of this json are in number format, for example “23.0”
I use this code

//Getting JSON from item
var String json = UPS_1_LOG_NEW.state.toString
//Update othe Item based on JSON
UPS_1_RUNTIME.postUpdate(transform("JSONPATH","$.upses[0].timeleft", json))

UPS_1_RUNTIME are number item, i got this error in the logs:
Cannot convert '98.0 Minutes' to a state type which item 'UPS_1_RUNTIME' accepts: [DecimalType, UnDefType].

This because in the string there is also the “MInutes”
It is possible to get only the number part of the string?
om a JSON string?
Many Thanks

Please post your JSON string.

	"status": "\ud83d\udc4d",
	"upses": [{
		"hitrans": "253.0 Volts",
		"nomoutv": "230 Volts",
		"bcharge": "99.0 Percent",
		"mintimel": "3 Minutes",
		"reg2": "0x00",
		"dlowbatt": "2 Minutes",
		"reg1": "0x00",
		"sense": "Low",
		"dipsw": "0x00",
		"nombattv": "24.0 Volts",
		"end apc": "2018-03-28 15:33:04 +0200",
		"lotrans": "196.0 Volts",
		"cumonbatt": "0 Seconds",
		"battv": "27.2 Volts",
		"hostname": "985f2df2bacc",
		"firmware": "70.11.I",
		"minlinev": "231.4 Volts",
		"pc": "001,051,1154",
		"version": "3.14.12 (29 March 2014) debian",
		"xoffbatt": "N/A",
		"selftest": "NO",
		"lastxfer": "Automatic or explicit self test",
		"outputv": "234.0 Volts",
		"battdate": "15/07/15",
		"statflag": "0x05000008",
		"alarmdel": "5 Seconds",
		"status": "ONLINE",
		"serialno": "QS01 3110863",
		"starttime": "2018-03-28 15:31:02 +0200",
		"umxfers": "0",
		"upsname": "UPS_MAIN",
		"tonbatt": "0 Seconds",
		"driver": "APC Smart UPS (any)",
		"stesti": "336",
		"reg3": "0x00",
		"dwake": "0 Seconds",
		"mbattchg": "5 Percent",
		"mandate": "01/16/01",
		"date": "2018-03-28 15:32:17 +0200",
		"maxtime": "0 Seconds",
		"linefreq": "50.0 Hz",
		"retpct": "0.0 Percent",
		"timeleft": "98.0 Minutes",
		"cable": "Custom Cable Smart",
		"linev": "234.0 Volts",
		"maxlinev": "235.3 Volts",
		"upsmode": "Stand Alone",
		"xtbatts": "0",
		"loadpct": "16.1 Percent",
		"model": "SMART-UPS 1400",
		"dshutd": "20 Seconds",
		"itemp": "30.1 C"

You can split the string in the rule.

 val wrongString = transform("JSONPATH","$.upses[0].timeleft" ,json)
 val goodValue = wrongString.split(" ").get(0)
 logInfo("JSON Test","Result:" + wrongString )
 logInfo("JSON Test","Result:" + goodValue )
1 Like

Thanks for your help it work great.
I found also anoteher way, and in this way the command only one line:

UPS_1_LINEVOLTAGE.postUpdate(transform("JSONPATH","$.upses[0].linev", json).replaceAll("[^\\.0123456789]",""))

It use string.replace and a regex to keep only numbers and the decimal separator.



When you feel better with a one liner, go ahead :wink:

transform("JSONPATH","$.upses[0].timeleft" ,json).split(" ").get(0)

As always there are multiple ways to achive one goal. Only thing which matters is that you have a working solution.


Thank you very much