3

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.

1
  • What are the quoting rules for the string? The answer depends on the quoting used. For example, if the string is JSON encoded JSON, then unmarshal twice. If the string uses Go quoting, use strconv.Unquote. Commented Jul 8, 2021 at 12:02

3 Answers 3

7

Wrap your incoming string before unquoting it like this:

s,err := strconv.Unquote(`"`+yourstring+`"`)

Then you can proceed with unmarshalling it.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

4 Comments

i got error: invalid character '\\' looking for beginning of object key string
I used a package where the function accept string as param, I read that param receiving this escaped json, convert it to rawmessage, unmarshall and got that error.
Raw message is []byte. It might've been easier to remove the backslashes.
you can try this when strconv.Unquote not work(got invalid syntax), thanks a lot
1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.