How to determine the type of json object in go

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

How to determine the type of json object in go

问题

gobyexample.com/json上,有一些示例展示了如何将json字符串解码为类型化对象或声明为map[string]interface{}的字典对象。但是它假设结果始终是一个字典。

所以我的问题是如何确定json对象的类型,以及处理它的最佳实践是什么?

英文:

In gobyexample.com/json, a few examples show how to decode json string into typed objects or dictionary objects, which are declared as map[string]interface{}. But it assumes the result is always a dictionary.

So my question is how to determine the type of json object and what is the best practice to handle that?

答案1

得分: 4

查看json.Unmarshal的定义:

func Unmarshal(data []byte, v interface{}) error

因此,至少可以通过使用反射来获取底层类型。

var v interface{}
json.Unmarshal([]byte(JSON_STR), &v)
fmt.Println(reflect.TypeOf(v), reflect.ValueOf(v))

而且,使用switch语句绝对是一种更好的做法。我认为下面的代码片段基本上可以满足你的要求。

switch result := v.(type) {
case map[string]interface{}:
    fmt.Println("dict:", result)
case []interface{}:
    fmt.Println("list:", result)
default:
    fmt.Println("value:", result)
}
英文:

Checkout the definition of json.Unmarshal:

func Unmarshal(data []byte, v interface{}) error

So at least you can obtain the underlying type by using reflect.

var v interface{}
json.Unmarshal([]byte(JSON_STR), &v)
fmt.Println(reflect.TypeOf(v), reflect.ValueOf(v))

And switch definitely is a better practice. I suppose below snippet

switch result := v.(type) {
case map[string]interface{}:
	fmt.Println("dict:", result)
case []interface{}:
	fmt.Println("list:", result)
default:
	fmt.Println("value:", result)
}

can basically meet your requirement.

huangapple
  • 本文由 发表于 2017年1月21日 23:24:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/41781052.html
匿名

发表评论

匿名网友

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

确定