当不使用结构体时,访问JSON属性的方法是什么?

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

Accessing JSON properties when not using struct

问题

我有一些 JSON 数据,我需要能够访问其中的属性。由于 JSON 的属性可能会变化,我无法创建一个 struct 来进行解组。

示例

JSON 可能是这样的:

{"name" : "John Doe", "email" : "john@doe.com"}

或者是这样的:

{"town" : "Somewhere", "email" : "john@doe.com"}

或者其他任何形式。

我该如何访问每个属性?

英文:

I have some JSON and I need to be able to access the properties. As the JSON properties can vary I can't create a struct to unmarshal into.

Example

The JSON could be this:

{"name" : "John Doe", "email" : "john@doe.com"}

or this:

{"town" : "Somewhere", "email" : "john@doe.com"}

or anything else.

How can I access each of the properties?

答案1

得分: 5

你可以将其解组为interface{}。如果这样做,json.Unmarshal将会将一个JSON对象解组为Go的map。

例如:

var untypedResult interface{}
err := json.Unmarshal(..., &untypedResult)

result := untypedResult.(map[string]interface{})

// ... 现在你可以遍历result的键和值 ...

请参考http://blog.golang.org/json-and-go#TOC_5.中的完整示例。

英文:

You can unmarshal it into an interface{}. If you do that, json.Unmarshal will unmarshal a JSON object into a Go map.

For example:

var untypedResult interface{}
err := json.Unmarshal(..., &untypedResult)

result := untypedResult.(map[string]interface{})

// ... now you can iterate over the keys and values of result ...

See <http://blog.golang.org/json-and-go#TOC_5.> for a complete example.

答案2

得分: 0

如果你恰好有一些可能未指定的字段,你可以将输入解组为带有指针的结构体。如果字段不存在,指针将为nil

package main

import (
	"encoding/json"
	"fmt"
)

type Foo struct {
	A *string
	B *string
	C *int
}

func main() {
	var input string = `{"A": "a","C": 3}`
	var foo Foo
	json.Unmarshal([]byte(input), &foo)
	fmt.Printf("%#v\n", foo)
}

Playground

如果你真的想要更灵活的方式,你也可以将输入解组为map[string]interface{}

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var input string = `{"A": "a","C": 3}`
	var foo map[string]interface{} = make(map[string]interface{})
	json.Unmarshal([]byte(input), &foo)
	fmt.Printf("%#v\n", foo)
}

Playground

英文:

If you just happen to have fields that may not be specified, you can unmarshal your input into a struct with pointer. If the field isn't present, the pointer will be nil.

package main

import (
	"encoding/json"
	"fmt"
)

type Foo struct {
	A *string
	B *string
	C *int
}

func main() {
	var input string = `{"A": "a","C": 3}`
	var foo Foo
	json.Unmarshal([]byte(input), &foo)
	fmt.Printf("%#v\n", foo)
}

Playground

If you really want something more flexible, you can also unmarshal your input into a map[string]interface{}.

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var input string = `{"A": "a","C": 3}`
	var foo map[string]interface{} = make(map[string]interface{})
	json.Unmarshal([]byte(input), &foo)
	fmt.Printf("%#v\n", foo)
}

Playground

答案3

得分: 0

在解组 JSON 文档时,并不需要在结构体中定义的所有属性都在 JSON 文档中存在。在你的示例中,你可以定义以下结构体:

type MyJson struct {
    Name  string `json:"name"`
    Town  string `json:"town"`
    Email string `json:"email"`
}

当你使用这个结构体来解组一个 JSON 文档时,如果其中一个或多个属性在 JSON 文档中缺失,它们将会被初始化为相应类型的空值(对于 string 属性来说,是一个空字符串)。

另外,你也可以使用通用的 interface{} 类型进行解组,然后使用类型断言。这在 博文 "JSON and GO" 中有详细的文档说明:

var jsonDocument interface{}

err := json.Unmarshal(jsonString, &jsonDocument)
m := jsonDocument.(map[string]interface{})
town := m["town"].(string)

注意:以上代码是用于解组 JSON 文档的示例,不需要翻译。

英文:

When unmarshalling a JSON document, not all properties that are defined in the struct need to be present in the JSON document. In your example, you could define the following struct:

type MyJson struct {
    Name string `json:"name"`
    Town string `json:"town"`
    Email string `json:"email"`
}

When your use this struct to unmarshal a JSON document that has one or more of these properties missing, they will be initialized with the respective type's null value (an empty string for string properties).

<hr>

Alternatively, you can use the generic interface{} type for unmarshalling and then use type assertions. This is documented in-depth in the blog post "JSON and GO":

var jsonDocument interface{}

err := json.Unmarshal(jsonString, &amp;jsonDocument)
map := jsonDocument.(map[string]interface{})
town := map[&quot;town&quot;].(string);

huangapple
  • 本文由 发表于 2016年1月2日 01:58:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/34558579.html
匿名

发表评论

匿名网友

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

确定