Recommand · July 15, 2021 0

How to convert escaped json into a struct

This question already has answers here:

decode json including json encoded strings

(1 answer)

Unmarshaling a stringified json

(1 answer)

Closed 1 hour ago.

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.

Some might do a custom unmarshal method, but I think its 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]
}