如何在Golang中解析结构体(structs)并打印结构体中的项?

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

how to parse structs in golang and print the items from the struct?

问题

这是一个类似的例子:https://stackoverflow.com/questions/35970395/parsing-json-in-golang-into-struct
我从服务器获取了一个JSON响应,我只需要获取特定的数据。
我创建了一个示例代码:

package main

import (
    "fmt"
    "encoding/json"
)

type response struct {
    Response []struct {
        Stats struct {
            A int `json:"a"`
            B float64 `json:"b"`
            C int `json:"c"`
            D float64 `json:"d"`
            E float64 `json:"e"`
            F float64 `json:"f"`
            G float64 `json:"g"`
            H float64 `json:"h"`
            I float64 `json:"i"`
            J float64 `json:"j"`
        } `json:"stats"`
        Data []struct {
            Num0 int64 `json:"0"`
            Num1 interface{} `json:"1"`
        } `json:"data"`
    } `json:"response"`
}


func main() {
    src := `
{
    "response": [{
            "stats": {
                "a": 458,
                "b": 302.3738,
                "c": 0,
                "d": 706.777,
                "e": 2.423,
                "f": 238.73375,
                "g": 68.971,
                "h": 85.1989781659389,
                "i": 84.6381777592766,
                "j": 292658.49
            },
            "data": [
                [1453222860000, null],
                [1453223160000, 3.769],
                [1453223220000, 37.464]
            ]
        }
    ]
}
`

    var g response
    json.Unmarshal([]byte(src), &g)
    fmt.Println(g.Response[0].Stats)  
}

我得到的输出是

{458 302.3738 0 706.777 2.423 238.73375 68.971 85.1989781659389 84.6381777592766 292658.49}

我想从stats结构中获取特定的项。假设我想打印stats结构中的A或J的值。我该如何做到这一点?
我实际上不需要data结构。我从服务器得到的JSON响应给了我这些数据,但我实际上不需要它们。无论如何,我的问题是如何只获取Stats结构中的特定项?

对于如何做到这一点或者改进我的结构格式,有什么建议吗?
谢谢!

英文:

Here is a similar example: https://stackoverflow.com/questions/35970395/parsing-json-in-golang-into-struct
I am getting a json response from the server and I only need to get certain data.
I've created a sample code:

package main

import (
    "fmt"
    "encoding/json"
)

type response struct {
	Response []struct {
		Stats struct {
			A int `json:"a"`
			B float64 `json:"b"`
			C int `json:"c"`
			D float64 `json:"d"`
			E float64 `json:"e"`
			F float64 `json:"f"`
			G float64 `json:"g"`
			H float64 `json:"h"`
			I float64 `json:"i"`
			J float64 `json:"j"`
		} `json:"stats"`
		Data []struct {
			Num0 int64 `json:"0"`
			Num1 interface{} `json:"1"`
		} `json:"data"`
	} `json:"response"`
}


func main() {
    src := `
{
    "response": [{
            "stats": {
                "a": 458,
                "b": 302.3738,
                "c": 0,
                "d": 706.777,
                "e": 2.423,
                "f": 238.73375,
                "g": 68.971,
                "h": 85.1989781659389,
                "i": 84.6381777592766,
                "j": 292658.49
            },
            "data": [
                [1453222860000, null],
                [1453223160000, 3.769],
                [1453223220000, 37.464]
            ]
        }
    ]
}
`
    
    var g response
    json.Unmarshal([]byte(src), &g)
    fmt.Println(g.Response[0].Stats)  
}

The output I get is

`{458 302.3738 0 706.777 2.423 238.73375 68.971 85.1989781659389 84.6381777592766 292658.49}

`

I want to get certain items from just the stat struct. Let's say I want to print the value of A or J from the stats struct. How do I do that?
I don't really need the data struct. The json response I got from the server gave me those data but I dont really need it. Anyway, my question is how do I get only certain items only in the Stats struct?

Any suggestion on how to do this or even improve my structs format?
Thanks!

答案1

得分: 1

你可以简单地忽略你不关心的结构部分。JSON包会在源JSON中忽略任何在目标结构中不存在的内容。因此,如果你不关心Data部分,可以将其从结构中省略。如果你只关心stats部分中的A和J,只需包含它们即可。

type response struct {
    Response []struct {
        Stats struct {
            A int `json:"a"`
            J float64 `json:"j"`
        } `json:"stats"`
    } `json:"response"`
}

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

另外值得注意的是,如果结构字段名的小写形式与JSON标签相同,你不需要包含结构标签。因为JSON包会匹配仅在大小写上有差异的字段(尽管它更喜欢精确匹配,如果存在歧义的话)。

英文:

You can simply omit any piece of the structure you don't care about. The JSON package will silently ignore anything present in the source JSON that isn't present in the destination structure. Thus if you don't care about the Data portion, omit it from the structure. If you only care about A and J in the stats section, only include those.

type response struct {
    Response []struct {
        Stats struct {
            A int `json:"a"`
            J float64 `json:"j"`
        } `json:"stats"`
    } `json:"response"`
}

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

Edit: Also worth noting that you don't need to include the struct tags if they are just lowercases of the field names, as the JSON package will match fields that only differ by capitalization (though it prefers exact matches, if there's ambiguity).

huangapple
  • 本文由 发表于 2017年2月7日 05:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/42077426.html
匿名

发表评论

匿名网友

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

确定