0

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.

alakin_11
  • 689
  • 6
  • 12

1 Answers1

1

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]
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Zombo
  • 1
  • 62
  • 391
  • 407