1
votes

I try to convert a make(map[string]string) into a yaml like that:

Yaml Output desire:

items:
    keys1:value1
    keys2:value2
    keys3:value3
    keys4:value4

The keys,values are this listKey map of string. J = string = {"key1":"value1","key2":"value2" }

type Items struct {
 items string
 ItemsValues map[string][]string
 }

func ConvertToYelm(j string){
y := Items{}

var dataJson map[string]string
err := json.Unmarshal([]byte(j), &dataJson)
if err != nil {
    fmt.Println(err)
    return
}
listKey := make(map[string]string)

for k := range dataJson{
   listKey[k] = k
}

yelm, err := yaml.Marshal(listKey)
if err != nil {
   fmt.Println(err)
   return
}
err = yaml.Unmarshal(yelm, Items)
if err != nil {
    fmt.Println(err)
    return
}
yeml2, err := yaml.Marshal(&yelm)
fmt.Printf ("%s", string(yeml2))

To be honest, I'm a little bit lost here, thank you for the help

1
Lost how? Please show all your code, including imports and sample data. Also show desired output and what you are actually getting. Your struct has a map of string to string slice, this doesn't look like the output your are expecting. - Marc

1 Answers

4
votes

To get the exact YAML from your post:

items:
    keys1:value1
    keys2:value2
    keys3:value3
    keys4:value4

You can do this (Go Playground):

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
)

type ItemsStruct struct {
    Items map[string]string `yaml:"items"`
}

func main() {
    itms := &ItemsStruct{Items: map[string]string{
        "keys1": "value1",
        "keys2": "value2",
        "keys3": "value3",
        "keys4": "value4"}}

    yamlBytes, err := yaml.Marshal(itms)
    if err != nil {
        //handle error
    }

    fmt.Println(string(yamlBytes))
}

And just to add, I see your code is decoding this JSON {"key1":"value1", "key2":"value2", ... } and then encoding it as YAML in your specified format. Here is the Go Playground for that.