英文:
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:Тестовый ключ]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论