Best way to create outbound mqtt message with json content?

I want to create a mqtt outbound message with json content that my Domoticz server understand.

Domoticz need json content where it can get idx and new state of switch like this:

{"command": "switchlight", "idx": 2450, "switchcmd": "On" }

The idx is unique like name in items on openHAB. So I was thinking of including idx in name on openHAB.
On and Off is case sensitive so ON and OFF will not work.

I tried to create this message with javascript and use it in my items-file like this:


The problem I have is to get the name of the switch in the javascript. I guess I can’t add more to the javascript function argument?

Is javascript the way to go or how do I solve it?

I think you might need to do this in a Rule and use Proxy Items.

Here is one example (there are many in the forum) of a rule sending a json payload to mqtt:

State is usually used in an inbound configuration in OH2. If you want to send the json payload you will need an outbound config.

See more here:

Do I have to write one rule for every item? Is it possible to make it universal as I want to do same thing everytime on all switches.

A example would be great with mqtt outbound message as I have hard to find something simular and have never used rules.

How do I get item name, state and so on in the rule?
And what do you meen with Proxy item?

Yes, this is possible and encouraged. I recommend looking at Design Pattern: Human Readable Names in Messages and Design Pattern: Associated Items for ways to achieve this.

Okey, This is how I solved it. Maybe it’s possible to do it even better.

rule "Send MQTT message on Light command"
	Member of gLight received command
	var idxStartPos ="idx") + 3
	var idxStopPos =
	var  myString = ""

	if (triggeringItem.state.toString() == "ON" || triggeringItem.state.toString() == "OFF")
		var cmd = triggeringItem.state.toString().toLowerCase.toFirstUpper()
		// {"command": "switchlight", "idx": 2450, "switchcmd": "On" }
		myString = '{\"command\": \"switchlight\", \"idx\": ' +,idxStopPos) + ', \"switchcmd\": \"' + cmd + '\"}'
		// {"command": "switchlight", "idx": 2450, "switchcmd": "Set Level", "level": 100 }
		myString = '{\"command\": \"switchlight\", \"idx\": ' +,idxStopPos) + ', \"switchcmd\": \"Set Level\", \"level\": ' + triggeringItem.state.toString() + '}'

	publish("mqttBroker", "domoticz/in", myString)
Switch idx123 "Outdoorlamp" (gLight) [ "Lighting" ] {mqtt="<[mqttBroker:domoticz/out:state:JS(get_state.js):(?s).*idx\".?.?.?123,.*]"}
Number Outdoor_Temperature "Temperature [%.1f]" <temperature> ["CurrentTemperature"] {mqtt="<[mqttBroker:domoticz/out:state:JSONPATH($.svalue1):(?s).*idx\".?.?.?124,.*]"}
    var parsed = JSON.parse(i);
    if (parsed.nvalue == 0)
        return "OFF"
    else if (parsed.nvalue == 1)
        return "ON"
    else if (parsed.nvalue == 2)
        return parsed.svalue1