简体   繁体   English

json.Unmarshal 忽略 json 字符串中的 json 字符串值,不要尝试解析它

[英]json.Unmarshal Ignore json string value inside a json string, dont attempt to parse it

I need to unmarshal a json string, but treat the 'SomeString' value as a string and not json.我需要解组 json 字符串,但将“SomeString”值视为字符串而不是 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.您的输入不是有效的 JSON。 See this part:请参阅此部分:

\"SomeString\":\"{\"test

There's a key SomeString and it has a value: {\ .有一个键SomeString ,它有一个值: {\ 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.随后的字符test不是SomeString值的一部分,它们显示为“单独”,但如果它们是下一个属性的名称,则必须引用它。 So you get the error invalid character 't' after object key:value pair .所以你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.当然可以有一个 JSON 字符串作为值并且它没有被解析,但是输入必须是有效的 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 ):使用此输入,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"}}}

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. ""已经是一个解释(Go)文字,你想要另一个 JSON 在里面转义字符串。 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 .这将与 output 相同,在Go Playground上尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM