Search code examples
jsonstringgoparsingyaml

How to parse a string of a yaml file's content in Go?


I have a json response where I need to extract the list of values for files and folders, however both the number of elements in each list and properties in the json response is not fixed as shown below:

JSON Response:

"config.yml" : "project: \n  files: \n    - file1\n    - file2\n  folders: \n    - folder1\n    - folder2\n  random1: \n  random2:\n    - redundant1"

How can I parse the string and extract the list for files and folders into a []string?

For reference: config.yml

project: 
  files: 
    - file1
    - file2
  folders: 
    - folder1
    - folder2
  random1: 
  random2:
    - redundant1

I tried just yaml.unmarshalling the string (https://go.dev/play/p/j0RvgHo3djI) but that doesn't work.

I'm moving on to try yaml.unmarshalling the string, then json.marshal and json.unmarshal to get a nested map but I am not sure if this is the right way to go about it.

Any help/guidance would be greatly appreciated!


Solution

  • This can be accomplished by tweaking your existing code — there are two issues with it:

    1. It's unmarshaling into []MyStruct but there's only one project. The files and folders are the only slices you need.
    2. It's not considering project at all. The decoder currently expects files and folders to be at the top-level of the YAML document.

    Here is the fixed version:

    package main
    
    import (
        "fmt"
    
        "github.com/goccy/go-yaml"
    )
    
    func main() {
        yml := "project: \n  files: \n    - file1\n    - file2\n  folders: \n    - folder1\n    - folder2\n  random1: \n  random2:\n    - redundant1"
        var resp MyStruct
        if err := yaml.Unmarshal([]byte(yml), &resp); err != nil {
            panic(fmt.Errorf("could not parse yaml from file. %w", err))
        }
    
        fmt.Println(&resp)
    }
    
    type MyStruct struct {
        Project struct {
            Files   []string `yaml:"files"`
            Folders []string `yaml:"folders"`
        } `yaml:"project"`
    }
    
    

    Play: https://go.dev/play/p/r8Q0kSx3NVc