英文:
How to convert escaped json into a struct
问题
我遇到了将转义的 JSON 对象转换为结构体的问题。
我面临的主要问题是 sources 字段的转义 JSON。
以下是保存的数据。
{
"key": "123",
"sources": "{\"1a\":\"source1a\",\"2b\":\"source2b\",\"3c\":\"source3c\",\"default\":\"sourcex\"}"
}
type config struct {
Key string `json:"key" validate:"required"`
Sources ???? `json:"sources" validate:"required"`
}
然后,我将有一个源值,并希望检查我的值是否在 JSON 中找到。
如果我的值是 "1a",则返回 "source1a",依此类推。
我还尝试在单元测试中编写这个功能。
英文:
I am having trouble converting an escaped json object into a struct.
The main problem I am facing is the escaped json for the sources field.
The following data is how it's being saved.
{
"key": "123",
"sources": "{\"1a\":\"source1a\",\"2b\":\"source2b\",\"3c\":\"source3c\",\"default\":\"sourcex\"}"
}
type config struct {
Key string `json:"key" validate:"required"`
Sources ???? `json:"sources" validate:"required"`
}
I then will have a source value and would like to check if my value is found in the json.
If my value is "1a" return "source1a", etc.
I'm trying to write this in a unit test as well.
答案1
得分: 1
有些人可能会使用自定义的解组方法,但我认为最简单的方法是进行两次解析:
package main
import (
"encoding/json"
"fmt"
)
const s = `
{
"key": "123",
"sources": "{\"1a\":\"source1a\",\"2b\":\"source2b\",\"3c\":\"source3c\",\"default\":\"sourcex\"}"
}
func main() {
var t struct{Key, Sources string}
json.Unmarshal([]byte(s), &t)
m := make(map[string]string)
json.Unmarshal([]byte(t.Sources), &m)
fmt.Println(m) // map[1a:source1a 2b:source2b 3c:source3c default:sourcex]
}
英文:
Some might do a custom unmarshal method, but I think it's easier just to do two passes:
package main
import (
"encoding/json"
"fmt"
)
const s = `
{
"key": "123",
"sources": "{\"1a\":\"source1a\",\"2b\":\"source2b\",\"3c\":\"source3c\",\"default\":\"sourcex\"}"
}
`
func main() {
var t struct{Key, Sources string}
json.Unmarshal([]byte(s), &t)
m := make(map[string]string)
json.Unmarshal([]byte(t.Sources), &m)
fmt.Println(m) // map[1a:source1a 2b:source2b 3c:source3c default:sourcex]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论