How do you convert YAML to JSON?

I’m still new enough to Node-RED and most tutorials out there tells me that I need to pull the JSON-data from the states UI and add it to my call service node if I want to set i.e. brightness or color on my lights, but HA only speaks YAML in the states UI now.

…and my search-fu fails me, I’ve done an honest effort trying to find the answer, I promise.

But it doesn’t matter
In the call service node it shows you all the field allowed for the service your using
And in states ui sure it looks different but really your only missing " " and the { }

If you google “yaml to json” you get a few online converters.

Or it’s a couple of lines of Python if you’re happy with that; let me know if needed!

Its like the kids of today can’t manually add up a total, or count backwards when giving change. If you cant do it manually how will you ever learn. You’ll pay zero notice to the structure cause you only ever copy and paste.

I think you’re right, I should get a hang of yaml <> JSON syntax conversion. I’ll get to it.

YAML:

data:
  entity_id: light.living_room
  brightness: 255

JSON:

{
  "data": {
    "entity_id": "light.living_room",
    "brightness": 255
  }
}

You can work the rest out from there :slight_smile:

3 Likes

Very clear and useful example, thanks alot! :slight_smile:

Here is a tool you could use https://www.json2yaml.com/

1 Like

A small point, but useful to know if you weren’t aware: JSON is technically a subset of YAML, so going the other way is easy. Valid JSON should be valid YAML.

In other words, you can use the square and curly brackets etc in YAML if you want to, e.g. to fit more things on one line; it’s just more readable to use line breaks, indentation, etc. And YAML offers lots of nice extras, like the ability to insert comments, which you can’t do in JSON (so it doesn’t work the other way around!)

But hence the general trend in the YAML direction, for anything that might be read or composed by humans.

Lastly, if you wanted to use python to print the JSON equivalent of the file “foo.yaml”, you can do something like:

import json
import yaml
print(
   json.dumps(
      yaml.load(open("foo.yaml")), 
      indent=2
   )
)

You might need to pip3 install pyyaml first.

1 Like