[英]json.Unmarshal Ignore json string value inside a json string, dont attempt to parse it
我需要解組 json 字符串,但將“SomeString”值視為字符串而不是 json。 嘗試此操作時的解組器錯誤不確定這是否可能。 謝謝。
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)
}
您的輸入不是有效的 JSON。 請參閱此部分:
\"SomeString\":\"{\"test
有一個鍵SomeString
,它有一個值: {\
。 其假定值內的第二個引號將其關閉。 隨后的字符test
不是SomeString
值的一部分,它們顯示為“單獨”,但如果它們是下一個屬性的名稱,則必須引用它。 所以你invalid character 't' after object key:value pair
。
當然可以有一個 JSON 字符串作為值並且它沒有被解析,但是輸入必須是有效的 JSON。
例如,使用原始字符串文字:
a := `{"Name":"Jim", "Description":"This is a test", "SomeString":"{\"test\":{\"test\":\"i am a test\"}}" }`
使用此輸入,output 將是(在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"}}}
這按預期工作,您的問題是您如何指定輸入。 ""
已經是一個解釋(Go)文字,你想要另一個 JSON 在里面轉義字符串。 在那種情況下,你必須逃脫兩次!
像這樣:
a := "{\"Name\":\"Jim\", \"Description\":\"This is a test\", \"SomeString\":\"{\\\"test\\\":{\\\"test\\\":\\\"i am a test\\\"}}\" }"
這將與 output 相同,在Go Playground上嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.