Reputation: 1063
Say I have this json string:
{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}
I want to convert above string into struct:
{
A string
B string
C string
D int
E string
}
Im not sure how to do that as I have do the quote and unquote but seems no success yet.
Upvotes: 3
Views: 6887
Reputation: 751
You can make use of Unquote
method of strconv
as suggested by mfathirirhas, I have created a small code depicting you scenario as follows:
package main
import (
"encoding/json"
"fmt"
"strconv"
)
type response struct {
A string
B string
C string
D int
E string
}
func main() {
str := (`"{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}"`)
fmt.Printf(str)
s, err := strconv.Unquote(str)
fmt.Println()
fmt.Println(s, err)
var resp response
if err := json.Unmarshal([]byte(s), &resp); err != nil {
panic(err)
}
fmt.Println(resp)
}
Output:
"{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}"
{"A":"a","B":"b","C":"c","D":2,"E":"e"} <nil>
{a b c 2 e}
Upvotes: 1
Reputation: 2287
Wrap your incoming string before unquoting it like this:
s,err := strconv.Unquote(`"`+yourstring+`"`)
Then you can proceed with unmarshalling it.
Upvotes: 7
Reputation: 51467
Somewhat of a hack, but the input string is how it would be encoded if it was in a JSON object, so you can do this:
x:=json.RawMessage(`"{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":2,\"E\":\"e\"}"`)
var v string
err:=json.Unmarshal(x,&v)
var x MyStruct
json.Unmarshal([]byte(v),&x)
Upvotes: 2