I need to unmarshal a json string, but treat the 'SomeString' value as a string and not json. The unmarshaler errors when attempting this Not sure if this is possible. Thanks.
type Test struct{
Name string `json:"Name"`
Description string `json:"Description"`
SomeString string `json:"SomeString"`
}
func main() {
a := "{\"Name\":\"Jim\", \"Description\":\"This is a test\", \"SomeString\":\"{\"test\":{\"test\":\"i am a test\"}}\" }"
var test Test
err := json.Unmarshal([]byte(a), &test)
if err !=nil{
fmt.Println(err)
}
fmt.Println(a)
fmt.Printf("%+v\n", test)
}
Your input is not a valid JSON. See this part:
\"SomeString\":\"{\"test
There's a key SomeString
and it has a value: {\
. The 2nd quote inside its supposed value closes it. The subsequent characters test
are not part of SomeString
's value, they appear "alone", but if they would be the name of the next property, it would have to be quoted. So you get the error invalid character 't' after object key:value pair
.
It's possible of course to have a JSON string as the value and it's not parsed, but the input must be valid JSON.
For example, using a raw string literal:
a := `{"Name":"Jim", "Description":"This is a test", "SomeString":"{\"test\":{\"test\":\"i am a test\"}}" }`
Using this input, the output will be (try it on the Go Playground ):
{"Name":"Jim", "Description":"This is a test", "SomeString":"{\"test\":{\"test\":\"i am a test\"}}" }
{Name:Jim Description:This is a test SomeString:{"test":{"test":"i am a test"}}}
This works as intended, your problem is how you specify your input. ""
is already an interpreted (Go) literal, and you want another, JSON escaped string inside it. In that case you'd have to escape twice!
Like this:
a := "{\"Name\":\"Jim\", \"Description\":\"This is a test\", \"SomeString\":\"{\\\"test\\\":{\\\"test\\\":\\\"i am a test\\\"}}\" }"
This will output the same, try it on the Go Playground .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.