如何将转义的 JSON 转换为结构体(struct)?

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

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]
}

huangapple
  • 本文由 发表于 2021年7月15日 10:33:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/68387201.html
匿名

发表评论

匿名网友

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

确定