TLang.Json / Yaml

TLang.Json and TLang.Yaml convert between Leaf trees and serialised text. Use them when you need to read structured data from a JSON or YAML string, or convert a Leaf model to JSON/YAML for inspection or output.

    use TLang.Json
    use TLang.Yaml
  

TLang.Json

Json.toLeaf parses a JSON string into a Leaf tree that you can traverse with Leaf.get and Leaf.keys.

      let rawJson = File.read("config.json")
      let leaf    = Json.toLeaf(rawJson)
      let host    = Leaf.get(leaf, "host")     // "localhost"
      let port    = Leaf.get(leaf, "port")     // "5432"
    

Json.fromLeaf serialises a Leaf tree to a JSON string.

      let leaf   = Leaf.model()
      let output = Json.fromLeaf(leaf)
      File.write("output/model.json", output, true)
    

TLang.Yaml

Yaml.toLeaf parses a YAML string into a Leaf tree.

      let rawYaml = File.read("values.yaml")
      let leaf    = Yaml.toLeaf(rawYaml)
      let image   = Leaf.get(leaf, "image")
    

Yaml.fromLeaf serialises a Leaf tree to a YAML string.

      let yamlStr = Yaml.fromLeaf(Leaf.model())
    

Example — Read Config, Generate Code

Read a JSON config file and generate an environment variable export script from it.

      use TLang.Json
      use TLang.Leaf
      use TLang.File
      use TLang.Terminal

      func main(): String {
          let raw    = File.read("config/settings.json")
          let config = Json.toLeaf(raw)
          let keys   = Leaf.keys(config)
          let result = ""

          for (k in keys) {
              let val    = Leaf.get(config, k)
              let result = result + "export " + k + "=" + val + "\n"
          }

          File.write("scripts/env.sh", result, true)
          Terminal.println("Generated env.sh with " + List.size(keys) + " variables")
          return "done"
      }