Loading a YAML nested map using SnakeYaml

2.7k views Asked by At

I am attempting to load a YAML file into a groovy program and have not been able to do so successfully. I would like to import a map with first, last middle name keys, whose values are names with a corresponding ethnicity value.

This is the code that I am trying to run:

    import java.util.List
    import java.util.ArrayList
    import java.io.FileInputStream
    import java.io.InputStream
    import org.yaml.snakeyaml.Yaml
    import java.util.Map
    import java.util.HashMap

    class BestRandomController {

         def index() {


                String gender, firstName, lastName
                List<String> firstNameList
                List<String> lastNameList
                Map<String, String> mapNames = new HashMap<String, String>()
                Map<String, Map <String, String>> mapPeople = new HashMap<String,Map <String,String>>()
                InputStream inputter = new FileInputStream(new File("/home/ian/Desktop/dataGeneration/vimNames.yaml"))




               Yaml sneakySnake = new Yaml()
               mapPeople=sneakySnake.load(inputter)

               render mapPeople

               render mapPeople.get('lastNames')

               mapNames = mapPeople.get('lastNames')

I am getting an error on the line "mapPeoople=sneakySnake.load(inputter)".

The error reads: "mapping values are not allowed here in 'reader', line 2, column 10: lastNames: ^ "

My yaml file that I am using for testing is this:

    ---#Names
    lastNames:
     Daghistani: White
     Terry: White
     Poksay: White
     Williams: White   
     Wade: Black

What can I do to make this work? I am wondering if it is an issue in the setup of my code or my YAML file, although my file seems pretty standard.

2

There are 2 answers

0
Anthon On

Your input file is not correct YAML as the first line contains a scalar ---#Names and that cannot be followed by mapping at the same indentation level.

If you intend for the first line to be a commented file separator use:

--- # Names
    lastNames:
     Daghistani: White
     Terry: White
     Poksay: White
     Williams: White
     Wade: Black

as a comment needs a space after # in YAML and you need to separate the document start marker (---) from the comment (examples in the official documentation are here).

If you intended ---#Names to be a scalar, then it cannot be juxtaposed next to a mapping. Either make it a mapping key itself (note the outdenting and the extra colon on the first line):

---#Names:
    lastNames:
     Daghistani: White
     Terry: White
     Poksay: White
     Williams: White
     Wade: Black

or make the two juxtaposted items a list:

   - ---#Names
   - lastNames:
     Daghistani: White
     Terry: White
     Poksay: White
     Williams: White
     Wade: Black
0
Andrey On

Just leave the delimiter alone or drop it:

#Names
lastNames:
 Daghistani: White
 Terry: White
 Poksay: White
 Williams: White
 Wade: Black