Custom JSON Nested Structure

http://play.golang.org/p/f6ilWnWTjm

I am trying to decode the next line, but only get null values.

How do I decode a nested JSON structure in Go?

I want to convert the following to display a data structure.

package main import ( "encoding/json" "fmt" ) func main() { jStr := ' { "AAA": { "assdfdff": ["asdf"], "fdsfa": ["1231", "123"] } } ' type Container struct { Key string 'json:"AAA"' } var cont Container json.Unmarshal([]byte(jStr), &cont) fmt.Println(cont) } 
+6
source share
2 answers

Use nested structures in Go to map nested structures in JSON.

Here is an example of how to handle your JSON example:

 package main import ( "encoding/json" "fmt" "log" ) func main() { jStr := ` { "AAA": { "assdfdff": ["asdf"], "fdsfa": ["1231", "123"] } } ` type Inner struct { Key2 []string `json:"assdfdff"` Key3 []string `json:"fdsfa"` } type Container struct { Key Inner `json:"AAA"` } var cont Container if err := json.Unmarshal([]byte(jStr), &cont); err != nil { log.Fatal(err) } fmt.Printf("%+v\n", cont) } 

link to playgrounds

You can also use an anonymous type for the internal structure:

 type Container struct { Key struct { Key2 []string `json:"assdfdff"` Key3 []string `json:"fdsfa"` } `json:"AAA"` } 

link to playgrounds

or both external and internal structures:

 var cont struct { Key struct { Key2 []string `json:"assdfdff"` Key3 []string `json:"fdsfa"` } `json:"AAA"` } 

link to playgrounds

If you do not know the field names in the internal structure, use a map:

 type Container struct { Key map[string][]string `json:"AAA"` } 

http://play.golang.org/p/gwugHlCPLK

There are more options. Hope this helps you on the right track.

+16
source

First of all: do not ignore errors returned by a function or method unless you have a good reason for doing so.

If you make the following changes to the code:

 err := json.Unmarshal([]byte(jStr), &cont) if err != nil { fmt.Println(err) } 

An error message will appear indicating why the value is empty:

json: cannot untie object in Go value of type string

Simply put: Key cannot be of type string , so you need to use a different type. You have several options for decoding them, depending on the characteristics of the Key value:

  • If the structure is static, use a different structure to match this structure.
  • If the structure is dynamic, use interface{} (or map[string]interface{} if it always has a JSON object type)
  • If the value is not accessible, only for use in later JSON encoding, or if decoding should be delayed, use json.RawMessage
+4
source

Source: https://habr.com/ru/post/1203107/


All Articles