Noob Node-RED question: how to access a value in JSON tree?

I saw a remark that the output of the eWeLink CUBE add-on in Node-RED doesn’t output a Javascript object. It does output a string. See Not getting any events in Node-Red - #7 by csongor.varga And that appearantly is the culprit.

It turns out easy to solve: just use the node that converts a JSON string to Javascript objects and then use the rest of the code.

Below is a visual representation of how I solved it. Maybe this explanation can help others to get started. I hope eWeLink will improve the output of their nodes to get objects instead of strings. In that way the JSON conversion won’t be necessary anymore.

1. The flow

  • At the left you see the “event - state” node. The device involved here is called “Maanlampjes” (litterally translated too “Little moon lights”, as they look like the half of a moon).
  • Then you see the JSON converter.
  • Then it splits up to a debug node and a switch node.
  • The first debug node just outputs all payload data that the JSON converter converted.
  • The switch checks whether the device has been switched on. Appearantly the iHost doesn’t send an “off” state, it only sends “on” or no “powerState” at all.
  • Then the “on” part of the switch goes to a debug node which only outputs a text “Switched on”.
  • The “not on” part of the switch goes to a debug node which only outputs a text “Switched off”.

2. JSON converter settings
002_JSON_decoder

  • You can convert to a string and Javascript object, but I only need the Javascript object and so at Action I choose Always convert to JavaScript Object.
  • I set Property to msg.payload.
  • The Name can be anything but I gave it a recognizable name.
  • The output will be just msg.payload again, but then converted into a Javascript Object.

3. Switch settings

  • At Name I gave it a recognizable name.
  • This time I only want to check for an on state at the JSON data at powerState. So at Property I filled in: msg.payload.power.powerState.
  • At the first rule I choose ==, then String and then I filled in on.
  • Then I added a second rule with the + add button below the list.
  • Then I choose !=, then String and again filled in on.
  • At the bottom I left the dropdown at checking all rules and left the recreate message sequences unticked.

4. Debug settings for on state
004_message_switch_on
This is just for the on state, but the off state is only 2 letters difference.

  • Output has been set to Expression and the contents is just the string Switched on. I felt more comfortable to open the extended editor by clickking on the ... button, but I believe that is not necessary.
  • At To I only ticked debug window.
  • At Name I again filled in a recognizable name.
1 Like