Search code examples
javascriptnode-red

How to match string in nested JSON using Switch node


Using Node-RED I receive this msg.payload (already) JSONified:

{ "name": "LightOnIntent", "slots": { "light": { "name": "light", "value": "kitchen" } } }

In my flow's first switch node I successfully match against msg.payload.name. The second switch should work with the contents of the slots, e.g. continue via 1 if msg.payload.slots contains "light".

I can't get it to work with a plain switch node. Even with specific array addressing, looking for "light" in msg.payload.slots[0] doesn't work. Do I need a function node to look for elements within the nested element?


Solution

  • First parse your json into object using JSON.parse().Then in your object slots.light is an object with keys name and value.Access key's values using object['key'] or object.key

    msg.payload.slots['light'].name;//matches against light
    msg.payload.slots['light'].value;//matches against kitchen
    

    Equivalent to

    msg.payload.slots.light.name;//matches against light
    msg.payload.slots.light.value;//matches against kitchen