0

I want to convert from string to object.

From

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

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": "{\n  \"key2\": \"value2\",\n  \"key3\": {\n    \"key4\": \"value4\"\n  }\n}\n"}`
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.

1
  • 1
    @kostix Thank you for editing. Commented Nov 3, 2017 at 5:14

1 Answer 1

3

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

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

3 Comments

I appreciate your answer. It worked fine. I couldn't notice to use struct. I accepted your answer as the solution. Thank you.
Yes. Thank you for adding more knowledge. I want to upvote more. But I had already upvoted. I'm sorry.
I am sorry. Can I ask you about problems of my question? I want to reflect them to my future questions. BTW, what I want to convert a string JSON to an object using golang is wrong?

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.