How to recieve JSON data?

Im dont understand how to recieve JSON data. Here code:

rule "Request data from narodmon"
	when
		Time cron "0/30 * * * * ?" 
	then
		var String json = ("http://narodmon.ru/api?cmd=sensorsValues&sensors=30241&uuid=9168dd80decbff888f85412c98adacee&api_key=34FKx6G9hhodY").toString
		var String var1= transform("JSONPATH", "$", json)
		postUpdate(temp1, var1)
end

In console write:

temp1 state updated to http://narodmon.ru/api?cmd=sensorsValues&sensors=30241&uuid=9168dd80decbff888f85412c98adacee&api_key=34FKx6G9hhodY

How to get “id” and "value, if result of this url issue this:

{"sensors":[{"id":30241,"value":6.5,"time":1445964810}]}

First you need to define some item for the response, for example like this one:

String Sensor_Data "Data" { http="<[http://narodmon.ru/api?cmd=sensorsValues&sensors=30241&uuid=9168dd80decbff888f85412c98adacee&api_key=34FKx6G9hhodY:60000:REGEX((.*))]" }

Then you need to parse this data to JSON:

var String data = Sensor_Data.state.toString
var String id = transform("JSONPATH", "$.sensors[0].id", data)
var String value = transform("JSONPATH", "$.sensors[0].value", data)

That’s it. :smile:
And don’t post any credentials on a forum…

Thanx! It works! And why write REGEX((.*))?
And how to make the operation of on-demand?

If you want it on demand then you need to use it in a rule like your original post. You can use sendHttpGetRequest(String url) to get the JSON data.

Thanx @danielwalters86! This code is work:

var String json = sendHttpGetRequest("http://narodmon.ru/api?cmd=sensorsValues&sensors=30241&uuid=9168dd80decbff888f85412c98adacee&api_key=34FKx6G9hhodY")
var String value = transform("JSONPATH", "$.sensors[0].value", json)

Big-big thanx!

1 Like

You can capture a value directly in item configuration using a regular expression. But in this case we capture the whole response and parse it in the rule.

1 Like

Sorry for humping this old thread - but I just found it looking for a good way to get JSON data in an OpenHAB item and I think I can still contribute something for people like myself who show up looking for help or answers…

Number VT_Http_YouLess_Total         "Stroomverbruik totaal [%,.3f kWh]"         <energy>    { http="<[http://youless/a?f=j:10000:JSONPATH($.cnt)]" }
Number VT_Http_YouLess_Current       "Stroomverbruik actueel [%,.0f Watt]"       <energy>    { http="<[http://youless/a?f=j:10000:JSONPATH($.pwr)]" }
Number VT_Http_YouLess_Signal        "Stroomverbruik signaal [%.0f %%]"          <energy>    { http="<[http://youless/a?f=j:10000:JSONPATH($.lvl)]" }

Using the JSONPATH transformation, you can get JSON data directly from a REST API like the one I use to get my YouLess power readings in OpenHAB.

1 Like