Golang equivalent to Python json.dumps and json.loads

Viewed 4379

This is a very weird situation but I need to convert a stringified json to something valid that I can unmarshall with:

"{\"hello\": \"hi\"}"

I want to be able to unmarshall this into a struct like this:

type mystruct struct {
    Hello string `json:"hello,string"`
}

I know normally the unmarshall takes bytes but Im trying to convert what I currently get into something structified. Any suggestions?

1 Answers

The issue is that the encoding/json package accepts well-formed JSON, in this case the initial JSON that you have has escaped quotes, first you have to unescape them, one way to do this is by using the strconv.Unquote function, here's a sample snippet:

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type mystruct struct {
    Hello string `json:"hello,omitempty"`
}

func main() {
    var rawJSON []byte = []byte(`"{\"hello\": \"hi\"}"`)

    s, _ := strconv.Unquote(string(rawJSON))

    var val mystruct
    if err := json.Unmarshal([]byte(s), &val); err != nil {
        // handle error
    }

    fmt.Println(s)
    fmt.Println(err)
    fmt.Println(val.Hello)
}
Related