尝试从JSON子部分中获取两个整数。

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

Trying to get 2 integers out of a JSON subsection

问题

我正在使用Golang中的VirusTotal HTTP API来获取URL的恶意和无害的投票。我想使用结构体来获取它们,然后使用这些结构体中的数据对URL进行解组。但是当我尝试这样做时,出现了以下错误:
cannot convert "harmless" (untyped string constant) to int

我目前正在使用的代码是:
type Votes struct {
harmless int
malicious int
}

type Attributes struct {
	votes []Votes `json:"total_votes"`
}

type data struct {
	attributes []Attributes `json:"attributes"`
}

type jsonstruct struct {
	data []data `json:"data"`
}

var printdata jsonstruct
fmt.Println(resp)
json.Unmarshal([]byte(body), &printdata)
fmt.Println(printdata.data[0].attributes[0].votes["harmless"])

我想要获取的JSON部分是:

{
"data": {
    "attributes": {
        "last_modification_date": 1642534694,
        "last_http_response_cookies": {
            "1P_JAR": "2022-01-18-19",
            "NID": "511=drq8-0Gwl0gpw2D-iyZhxrizpE--UMOyc_bO381XXkxknypvl_IETvsxRw3p8kMlBtiYEuSbASKK1wHirmgxce79kgzGMg9MryT0PnHox6kWbmEQTe2vsv_HtVZDFDXiLt4HKpcyDczOT8c_OK8bPb_P-f8rbIXJu_xrA0Ce4lw",
            "SameSite": "none"
        },
        "times_submitted": 82289,
        "total_votes": {
            "harmless": 54,
            "malicious": 18
        },

如你所见,我想要获取total_votes子部分的内容,即harmlessmalicious这两个整数。简而言之,我如何在不出现关于它们是未定义字符串的错误的情况下获取它们?

英文:

I'm using the VirusTotal HTTP API in Golang to get the votes on an URL, both malicious and harmless.
I want to get them using structs, and then unmarshaling the URL using data from these structs. But when I try that, this error shows up:
cannot convert "harmless" (untyped string constant) to int

The code I am currently using is:
type Votes struct {
harmless int
malicious int
}

type Attributes struct {
	votes []Votes `json:"total_votes"`
}

type data struct {
	attributes []Attributes `json:"attributes"`
}

type jsonstruct struct {
	data []data `json:"data"`
}

var printdata jsonstruct
fmt.Println(resp)
json.Unmarshal([]byte(body), &printdata)
fmt.Println(printdata.data[0].attributes[0].votes["harmless"])

And the part of the JSON that I want to get is:

{
"data": {
    "attributes": {
        "last_modification_date": 1642534694,
        "last_http_response_cookies": {
            "1P_JAR": "2022-01-18-19",
            "NID": "511=drq8-0Gwl0gpw2D-iyZhxrizpE--UMOyc_bO381XXkxknypvl_IETvsxRw3p8kMlBtiYEuSbASKK1wHirmgxce79kgzGMg9MryT0PnHox6kWbmEQTe2vsv_HtVZDFDXiLt4HKpcyDczOT8c_OK8bPb_P-f8rbIXJu_xrA0Ce4lw",
            "SameSite": "none"
        },
        "times_submitted": 82289,
        "total_votes": {
            "harmless": 54,
            "malicious": 18
        },

As you can see, I want to get the contents of the subsection total_votes, which are integers harmless and malicious. In short, how can I get them without getting the error about them being untyped strings?

答案1

得分: 1

你需要定义一个与 JSON 结构匹配的有效数据结构。在 Unmarshal 之后,你可以通过 res.Data.Attributes.TotalVotes.Harmless 访问投票字段。例如(https://go.dev/play/p/YCtV1u-KF7Y):

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Result struct {
	Data struct {
		Attributes struct {
			LastHTTPResponseCookies struct {
				OnePJAR  string `json:"1P_JAR"`
				Nid      string `json:"NID"`
				SameSite string `json:"SameSite"`
			} `json:"last_http_response_cookies"`
			LastModificationDate float64 `json:"last_modification_date"`
			TimesSubmitted       float64 `json:"times_submitted"`
			TotalVotes           struct {
				Harmless  float64 `json:"harmless"`
				Malicious float64 `json:"malicious"`
			} `json:"total_votes"`
		} `json:"attributes"`
	} `json:"data"`
}

var input = `{
"data": {
    "attributes": {
        "last_modification_date": 1642534694,
        "last_http_response_cookies": {
            "1P_JAR": "2022-01-18-19",
            "NID": "pcyDczOT8c_OK8bPb_P-f8rbIXJu_xrA0Ce4lw",
            "SameSite": "none"
        },
        "times_submitted": 82289,
        "total_votes": {
            "harmless": 54,
            "malicious": 18
        }
    }
}
}`

func main() {
	var res Result
	if err := json.Unmarshal([]byte(input), &res); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v", res.Data.Attributes.TotalVotes.Harmless)
}
英文:

You need to define valid data structure that matches json structure. And after Unmarshal you can access votes fields as res.Data.Attributes.TotalVotes.Harmless . For example (https://go.dev/play/p/YCtV1u-KF7Y):

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Result struct {
	Data struct {
		Attributes struct {
			LastHTTPResponseCookies struct {
				OnePJAR  string `json:"1P_JAR"`
				Nid      string `json:"NID"`
				SameSite string `json:"SameSite"`
			} `json:"last_http_response_cookies"`
			LastModificationDate float64 `json:"last_modification_date"`
			TimesSubmitted       float64 `json:"times_submitted"`
			TotalVotes           struct {
				Harmless  float64 `json:"harmless"`
				Malicious float64 `json:"malicious"`
			} `json:"total_votes"`
		} `json:"attributes"`
	} `json:"data"`
}

var input = `{
"data": {
    "attributes": {
        "last_modification_date": 1642534694,
        "last_http_response_cookies": {
            "1P_JAR": "2022-01-18-19",
            "NID": "pcyDczOT8c_OK8bPb_P-f8rbIXJu_xrA0Ce4lw",
            "SameSite": "none"
        },
        "times_submitted": 82289,
        "total_votes": {
            "harmless": 54,
            "malicious": 18
        }
    }
}
}
`

func main() {
	var res Result
	if err := json.Unmarshal([]byte(input), &res); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v", res.Data.Attributes.TotalVotes.Harmless)
}

huangapple
  • 本文由 发表于 2022年1月19日 03:43:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/70761526.html
匿名

发表评论

匿名网友

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

确定