How to create map variable from string literal in Golang?

Issue

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?

Solution

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:Тестовый ключ]]

Answered By – icza

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.