How to create map variable from string literal in Golang?

huangapple go评论80阅读模式
英文:

How to create map variable from string literal in Golang?

问题

我有一个准备好的地图结构,它是一个字符串文字。请注意,它不是 JSON!(看一下块的最后一个元素中的逗号)

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

我想将这个字符串转换为地图类型map[string]map[string]string)的实际值。我需要它用于测试。这可能吗?

英文:

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?

答案1

得分: 2

如果这只是用于测试,我会从源字符串中删除“不必要”的逗号,并使用JSON解组。

要删除不必要的逗号:我会使用正则表达式,\s*},将其替换为单个}

例如:

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)

输出结果(在Go Playground上尝试):

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

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

huangapple
  • 本文由 发表于 2022年2月17日 17:09:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/71155198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定