In this Knowledge Base post, I will leave 2 pieces of very simple and extremely similar code, how to read and write Yamls or Jsons, either by loading files or variables.

Groovy uses two very similar libraries for both formats, so you will see that the codes are very similar, only changing the variable names and the library.

What differs between the two is the conversion part of a class or map and the way this value is translated, the rest, even the recording of files, is also the same way.

In both codes, in the example below the variable readings are commented and the file readings are active, you can work however you need.

devops-db.info.yaml:

version: 1
group: infrastructure
tech: dns 
service: devops-db.info
description: Blueprint with DNS zones from devops-db.info
nameservers:
  - name: ns1.devops-db.info
    class: IN
    type: A    
    destination: 172.21.5.72
admin: admin.devops-db.info
serial_number: 2022122800
time_to_refresh: 12h
time_to_retry: 15m
time_to_expire: 3w
minimum_ttl: 2h
zones:
  - host: ldap
    class: IN
    type: A
    destination: 172.21.5.150
  - host: registry
    class: IN
    type: A
    destination: 172.21.5.151

read_yaml.groovy:

import groovy.yaml.YamlBuilder
import groovy.yaml.YamlSlurper

def str_Yaml = '''
version: 1
group: infrastructure
tech: dns
service: devops-db.info
zones:
  - host: ldap
    class: IN
    type: A
    destination: 172.21.5.150
  - host: registry
    class: IN
    type: A
    destination: 172.21.5.151
'''

def str_YamlFile = 'devops-db.info.yaml'
File obj_File = new File(str_YamlFile)

def yaml_Load = new YamlSlurper().parseText(obj_File.getText())
//def yaml_Load = new YamlSlurper().parseText(str_Yaml)

println('Resource: ' + yaml_Load['group'] + '.' + yaml_Load['tech'])
println('Domain: ' + yaml_Load['service'])

yaml_Load['zones'].each {item -> {
    println('Host: ' + item['host'] + ' - Destination: ' + item['destination'])
}}


// #######################################################################################################################
// Convert Map to Json
// prettyPrint a Json content

def map_Yaml = [
        version: 1,
        group: "infrastructure",
        tech: "dns",
        service: "devops-db.info",
        zones: [[
                        host: "ldap",
                        class: "IN",
                        type: "A",
                        destination: "172.21.5.150"],
                [
                        host: "registry",
                        class: "IN",
                        type: "A",
                        destination: "172.21.5.151"
                ]
        ]
]
def obj_YamlBuilder = new YamlBuilder()
obj_YamlBuilder(map_Yaml)

str_Yaml = obj_YamlBuilder.toString()
println(str_Yaml)

// #######################################################################################################################
// Write Json Content
// It's better to use the contents of prettyPrint()

str_YamlFile = 'v2.devops-db.info.yaml'
File obj_YamlFile = new File(str_YamlFile)
obj_YamlFile.write(str_Yaml)

Results:

Resource: infrastructure.dns
Domain: devops-db.info
Host: ldap - Destination: 172.21.5.150
Host: registry - Destination: 172.21.5.151
---
version: 1
group: "infrastructure"
tech: "dns"
service: "devops-db.info"
zones:
- host: "ldap"
  class: "IN"
  type: "A"
  destination: "172.21.5.150"
- host: "registry"
  class: "IN"
  type: "A"
  destination: "172.21.5.151"

devops-db.info.json

{
  "version": 1,
  "group": "infrastructure",
  "tech": "dns",
  "service": "devops-db.info",
  "description": "Blueprint with DNS zones from devops-db.info",
  "nameservers": [
    {
      "name": "ns1.devops-db.info",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.72"
    }
  ],
  "admin": "admin.devops-db.info",
  "serial_number": 2022122800,
  "time_to_refresh": "12h",
  "time_to_retry": "15m",
  "time_to_expire": "3w",
  "minimum_ttl": "2h",
  "zones": [
    {
      "host": "ldap",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.150"
    },
    {
      "host": "registry",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.151"
    }
  ]
}

read_json.groovy

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

// #######################################################################################################################
// Read Json content

def str_Json = '''
{
  "version": 1,
  "group": "infrastructure",
  "tech": "dns",
  "service": "devops-db.info",
  "zones": [
    {
      "host": "ldap",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.150"
    },
    {
      "host": "registry",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.151"
    }
  ]
}
'''

def str_JsonFile = 'devops-db.info.json'
File obj_File = new File(str_JsonFile)

def map_Load_Json = new JsonSlurper().parseText(obj_File.getText())
//def map_Load_Json = new JsonSlurper().parseText(str_Json)

println('Resource: ' + map_Load_Json['group'] + '.' + map_Load_Json['tech'])
println('Domain: ' + map_Load_Json['service'])

map_Load_Json['zones'].each {item -> {
    println('Host: ' + item['host'] + ' - Destination: ' + item['destination'])
}}

// #######################################################################################################################
// Convert Map to Json
// prettyPrint a Json content

def map_Json = [
        version: 1,
        group: "infrastructure",
        tech: "dns",
        service: "devops-db.info",
        zones: [[
                        host: "ldap",
                        class: "IN",
                        type: "A",
                        destination: "172.21.5.150"],
                [
                        host: "registry",
                        class: "IN",
                        type: "A",
                        destination: "172.21.5.151"
                ]
        ]
]

str_Json = JsonOutput.toJson(map_Json)
println(str_Json)

str_PP_Json = JsonOutput.prettyPrint(str_Json)
println(str_PP_Json)

// #######################################################################################################################
// Write Json Content
// It's better to use the contents of prettyPrint()

str_JsonFile = 'v2.devops-db.info.json'
File obj_JsonFile = new File(str_JsonFile)
obj_JsonFile.write(str_PP_Json)

Results:

Resource: infrastructure.dns
Domain: devops-db.info
Host: ldap - Destination: 172.21.5.150
Host: registry - Destination: 172.21.5.151
{"version":1,"group":"infrastructure","tech":"dns","service":"devops-db.info","zones":[{"host":"ldap","class":"IN","type":"A","destination":"172.21.5.150"},{"host":"registry","class":"IN","type":"A","destination":"172.21.5.151"}]}
{
    "version": 1,
    "group": "infrastructure",
    "tech": "dns",
    "service": "devops-db.info",
    "zones": [
        {
            "host": "ldap",
            "class": "IN",
            "type": "A",
            "destination": "172.21.5.150"
        },
        {
            "host": "registry",
            "class": "IN",
            "type": "A",
            "destination": "172.21.5.151"
        }
    ]
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.