Home > front end >  How to create map variable from string literal in Golang?
How to create map variable from string literal in Golang?

Time:02-17

I have a prepared map structure as a string literal. Notice, it is not a JSON! (look at commas in the last elements of blocks)

dict := `{
    "ru": {
        "test_key": "Тестовый ключ",
        "some_err": "Произошла ошибка",
    },
    "en": {
        "test_key": "Test key",
        "some_err": "Error occurs",
    },
}`

I want to transform this string to real value of map type (map[string]map[string]string). I need it for tests. Is it possible?

CodePudding user response:

If this is just for testing, I would remove the "unneeded" commas from the source string and use JSON unmarshaling.

To remove the unneeded commas: I'd use the regexp ,\s*}, and replace it with a single }.

For example:

dict = regexp.MustCompile(`,\s*}`).ReplaceAllLiteralString(dict, "}")

var m map[string]map[string]string
if err := json.Unmarshal([]byte(dict), &m); err != nil {
    panic(err)
}
fmt.Println(m)

Output (try it on the Go Playground):

map[en:map[some_err:Error occurs test_key:Test key] ru:map[some_err:Произошла ошибка test_key:Тестовый ключ]]
  • Related