Decoding json in golang without declaring type relationship?

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

Decoding json in golang without declaring type relationship?

问题

我不想指定我的 JSON 类型,因为它们非常混乱和复杂,我只想将它们加载到内存中,并在需要时进行查找。

在像 Python 这样的动态语言中很容易实现,例如:

data := make(map[string]interface{})
err := json.Unmarshal([]byte(str), &data)
if val, ok := data["foo"]; ok {
    ...
}

在 Go 中如何实现相同的功能?

英文:

I don't want to specify the type of my json since they are so messy and so complicated, I just want them to load into memory and I perform the lookup when needed.

It is easy with dynamic language such as python, e.g.

data = json.loads(str)
if "foo" in data:
   ...

How to do the same in go?

答案1

得分: 1

你可以将数据解码为interface{}类型,以解析任意的 JSON 数据。

参考以下示例代码,来自于 http://blog.golang.org/json-and-go

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
if err := json.Unmarshal(b, &f); err != nil {
    // 处理错误
}

你需要使用类型断言来访问以这种方式解码的数据例如

age := f.(map[string]interface{})["Age"].(int)

注意:以上代码中的 " 是 HTML 实体编码,实际使用时应该替换为双引号 "

英文:

You can unmarshal into an interface{} value to decode arbitrary JSON.

Taking the example from http://blog.golang.org/json-and-go

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
if err := json.Unmarshal(b, &f); err != nil {
    ... handle error
}

You need to use a type switch to access data decoded in this way. For example:

age := f.(map[string)interface{})["Age"].(int)

答案2

得分: 0

这是一个对我来说似乎更容易理解的例子,希望对你也有用:
https://gobyexample.com/json。查找单词"arbitrary"。

英文:

Here's an example which seems easier to understand for me, I hope it works for you too:
https://gobyexample.com/json . Look for the word "arbitrary"

huangapple
  • 本文由 发表于 2014年5月1日 17:10:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/23404905.html
匿名

发表评论

匿名网友

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

确定