Home > front end >  How to decide what struct is proper to accommodate a json file
How to decide what struct is proper to accommodate a json file

Time:09-25

I have a json file, which looks like below:

{
   "Key1": "value1",
   "Key2": [
      "value2",
      "value3",
   ],
}

I tried to use below struct to deserialize the json, however, after deserialization, only key2 has value, key1 was empty.

Question: what is the proper struct to deserialize this json?

data := map[string][]string{}
_ = json.Unmarshal([]byte(file), &data)

CodePudding user response:

You can decode that Json into a map[string]interface{}, or a struct modeling the data, or even just an empty interface{}

I typically use a struct because it avoids any need for me to do type assertions (the decoder handles that stuff).

Finally, if you can't for whatever reason immediately decode into a struct, I've found this library to be quite helpful: https://github.com/mitchellh/mapstructure

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type Data struct {
    Key1 string
    Key2 []string
}

func main() {
    var data = `{
   "Key1": "value1",
   "Key2": [
      "value2",
      "value3"
   ]
}`
    mapdata := make(map[string]interface{})
    var inter interface{}
    obj := Data{}
    if err := json.
        NewDecoder(bytes.NewBufferString(data)).
        Decode(&mapdata); err != nil {
        panic(err)
    } else {
        fmt.Printf("Decoded to map: %#v\n", mapdata)
    }
    if err := json.
        NewDecoder(bytes.NewBufferString(data)).
        Decode(&inter); err != nil {
        panic(err)
    } else {
        fmt.Printf("Decoded to interface: %#v\n", inter)
    }
        if err := json.
        NewDecoder(bytes.NewBufferString(data)).
        Decode(&obj); err != nil {
        panic(err)
    } else {
        fmt.Printf("Decoded to struct: %#v\n", obj)
    }
}

Decoded to map: map[string]interface {}{"Key1":"value1", "Key2":[]interface {}{"value2", "value3"}}
Decoded to interface: map[string]interface {}{"Key1":"value1", "Key2":[]interface {}{"value2", "value3"}}
Decoded to struct: main.Data{Key1:"value1", Key2:[]string{"value2", "value3"}}

https://play.golang.org/p/K31dAVtWJNU

CodePudding user response:

Using struct

type Test struct {
  Key1 string
  Key2 []string
}

func main() {
  testJson := `{"Key1": "value1","Key2": ["value2","value3"]}`
  var test Test 
  json.Unmarshal([]byte(testJson), &test)
  fmt.Printf("%s, %s", test.Key1 , test.Key2 )
}

Demo

Using a map

We create a map of strings to empty interfaces:

var result map[string]interface{}
testJson := `{"Key1": "value1","Key2": ["value2","value3"]}`
var result map[string]interface{}
json.Unmarshal([]byte(testJson ), &result)

Demo

  •  Tags:  
  • go
  • Related