从JSON字符串值解析JSON

问题描述:

I want to convert from string to object.

From

{"key1": "{
  \"key2\": \"value2\",
  \"key3\": {
    \"key4\": \"value4\"
  }
}
"}

To

{"key1": {"key2": "value2", "key3": {"key4": "value4"}}}

Finally, I want to get value4.

I can get the value of "key1" using below script.

jsondata := `{"key1": "{
  \"key2\": \"value2\",
  \"key3\": {
    \"key4\": \"value4\"
  }
}
"}`
var m map[string]interface{}
json.Unmarshal([]byte(jsondata), &m)
value := m["key1"]
fmt.Println(value)

https://play.golang.org/p/4lwgQJfp5S

But I can't convert the value to an object. So I can't get "value4". Are there methods for this? I can get it by regex like https://play.golang.org/p/6TB-qNAdgQ But now this is not my solution.

Thank you so much for your time and advices. And I'm sorry for my immature question.

There are two levels of JSON encoding. The first step is to decode the outer JSON value. Decode to a struct matching the structure of the JSON.

var outer struct{ Key1 string }
if err := json.Unmarshal([]byte(jsondata), &outer); err != nil {
    log.Fatal(err)
}

The next step is to decode the inner JSON value. Again, decode to a struct matching the structure of the JSON.

var inner struct{ Key3 struct{ Key4 string } }
if err := json.Unmarshal([]byte(outer.Key1), &inner); err != nil {
    log.Fatal(err)
}
// The value is inner.Key3.Key4

playground example

If the JSON is not double encoded, you can decode in one shot:

jsondata := `{"key1": { "key2": "value2",  "key3": { "key4": "value4"  }}}`
var v struct {
    Key1 struct{ Key3 struct{ Key4 string } }
}
if err := json.Unmarshal([]byte(jsondata), &v); err != nil {
    log.Fatal(err)
}
// value is v.Key1.Key3.Key4

playground example