How to decide what struct is proper to accommodate a json file

huangapple go评论94阅读模式
英文:

How to decide what struct is proper to accommodate a json file

问题

我有一个json文件,看起来像下面这样:

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

我尝试使用下面的结构体来反序列化这个json,但是在反序列化之后,只有key2有值,key1是空的。

**问题:**正确的结构体是什么,可以用来反序列化这个json?

data := struct {
    Key1 string
    Key2 []string
}{}
_ = json.Unmarshal([]byte(file), &data)
英文:

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)

答案1

得分: 0

使用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 )
}

演示

使用map

我们创建一个字符串到空接口的映射:

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

演示

英文:

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

答案2

得分: 0

你可以将该JSON解码为map[string]interface{},或者使用一个模拟数据的struct,甚至只是一个空的interface{}

通常我会使用struct,因为它避免了我需要进行类型断言的需要(解码器会处理这些内容)。

最后,如果由于某种原因无法立即解码为struct,我发现这个库非常有帮助: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

英文:

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

huangapple
  • 本文由 发表于 2021年9月25日 08:53:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/69322334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定