function to print from from a Json each item using a for loop golang

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

function to print from from a Json each item using a for loop golang

问题

这是一个Go语言的代码片段,它包含了一些结构体和函数。根据你的描述,你想要将jitem作为变量传递,并且在printitem函数中使用它。然而,根据代码中的定义,jitem并不是一个结构体的字段或方法,所以会导致错误。

要解决这个问题,你可以修改printitem函数,将jitem作为参数传递,并使用反射来获取结构体中对应字段的值。下面是修改后的代码:

  1. import "reflect"
  2. func printitem(r Response, jitem string) []string {
  3. item := []string{}
  4. for _, p := range r.Result {
  5. value := reflect.ValueOf(p)
  6. field := reflect.Indirect(value).FieldByName(jitem)
  7. if field.IsValid() {
  8. item = append(item, jitem+":"+field.String())
  9. }
  10. }
  11. return item
  12. }

这样修改后,printitem函数会使用反射来获取结构体中对应字段的值,并将其添加到item切片中返回。

希望这可以帮助到你!如果你还有其他问题,请随时提问。

英文:
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. )
  8. type Response struct {
  9. Status string `json:"status"`
  10. Message string `json:"message"`
  11. Result []struct {
  12. BlockNumber string `json:"blockNumber"`
  13. TimeStamp string `json:"timeStamp"`
  14. Hash string `json:"hash"`
  15. Nonce string `json:"nonce"`
  16. BlockHash string `json:"blockHash"`
  17. TransactionIndex string `json:"transactionIndex"`
  18. From string `json:"from"`
  19. To string `json:"to"`
  20. Value string `json:"value"`
  21. Gas string `json:"gas"`
  22. GasPrice string `json:"gasPrice"`
  23. IsError string `json:"isError"`
  24. TxreceiptStatus string `json:"txreceipt_status"`
  25. Input string `json:"input"`
  26. ContractAddress string `json:"contractAddress"`
  27. CumulativeGasUsed string `json:"cumulativeGasUsed"`
  28. GasUsed string `json:"gasUsed"`
  29. Confirmations string `json:"confirmations"`
  30. } `json:"result"`
  31. }
  32. func getapi(wallet string) ([]byte, error) {
  33. res, err := http.Get("https://api.bscscan.com/api?module=account&action=txlist&address=" + wallet + "&startblock=0&endblock=99999999&sort=asc&apikey=5Q4SS1XHV95SIPSCKK1FKCPGJSMRM2EI1K")
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. defer res.Body.Close()
  38. return ioutil.ReadAll(res.Body)
  39. }
  40. func j_unm(body []byte) Response {
  41. var r Response
  42. err := json.Unmarshal(body, &r)
  43. if err != nil {
  44. log.Println("Error unmarshalling json data:", err)
  45. }
  46. return r
  47. }
  48. func printitem(r Response, jitem string) []string {
  49. item := []string{}
  50. for _, p := range r.Result {
  51. item = append(item, jitem+":"+p.jitem)
  52. }
  53. return item
  54. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. gettrx, _ := getapi("0xf287E9f40f96C0cbAEAdD29Cf22E6CF5cC66030b")
  5. fmt.Println(printitem(j_unm(gettrx), "BlockNumber"))
  6. }

I want to pass as jitem as variable. I got the following error.

jitem is define as string, could be BlockNumber or TimeStamp

p.jitem undefined (type struct{BlockNumber string "json:\"blockNumber\""; TimeStamp string "json:\"timeStamp\""; Hash string "json:\"hash\""; Nonce string "json:\"nonce\""; BlockHash string "json:\"blockHash\""; TransactionIndex string "json:\"transactionIndex\""; From string "json:\"from\""; To string "json:\"to\""; Value string "json:\"value\""; Gas string "json:\"gas\""; GasPrice string "json:\"gasPrice\""; IsError string "json:\"isError\""; TxreceiptStatus string "json:\"txreceipt_status\""; Input string "json:\"input\""; ContractAddress string "json:\"contractAddress\""; CumulativeGasUsed string "json:\"cumulativeGasUsed\""; GasUsed string "json:\"gasUsed\""; Confirmations string "json:\"confirmations\""} has no field or method jitem)compilerMissingFieldOrMethod

答案1

得分: 1

p.jitem 是字符串吗?如果是字符串类型,可以将其转换为字符串,然后使用 string(p.jitem)

  1. func printitem(r Response, jItem string) []string {
  2. items := make([]string, 0)
  3. for _, p := range r.Result {
  4. items = append(items, jItem+":"+ string(p.jItem))
  5. }
  6. return items
  7. }
英文:

is p.jitem is string? if is this type is convertible to string,then use string(p.jitem)

  1. func printitem(r Response, jItem string) []string {
  2. //item := []string{}
  3. items:= make([]string,0)
  4. for _, p := range r.Result {
  5. items = append(items, jItem+":"+ string(p.jItem))
  6. }
  7. return items

答案2

得分: 0

你想要这个吗?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. )
  9. type Response struct {
  10. Status string `json:"status"`
  11. Message string `json:"message"`
  12. Result []map[string]string `json:"result"`
  13. }
  14. func getapi(wallet string) ([]byte, error) {
  15. res, err := http.Get("https://api.bscscan.com/api?module=account&action=txlist&address=" + wallet + "&startblock=0&endblock=99999999&sort=asc&apikey=5Q4SS1XHV95SIPSCKK1FKCPGJSMRM2EI1K")
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. defer res.Body.Close()
  20. return ioutil.ReadAll(res.Body)
  21. }
  22. func j_unm(body []byte) Response {
  23. var r Response
  24. err := json.Unmarshal(body, &r)
  25. if err != nil {
  26. log.Println("Error unmarshalling json data:", err)
  27. }
  28. return r
  29. }
  30. func printitem(r Response, jitem string) []string {
  31. item := []string{}
  32. for _, p := range r.Result {
  33. item = append(item, jitem+":"+p[jitem])
  34. }
  35. return item
  36. }
  37. func main() {
  38. gettrx, _ := getapi("0xf287E9f40f96C0cbAEAdD29Cf22E6CF5cC66030b")
  39. fmt.Println(printitem(j_unm(gettrx), "blockNumber"))
  40. }
英文:

do you want this?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. )
  9. type Response struct {
  10. Status string `json:"status"`
  11. Message string `json:"message"`
  12. Result []map[string]string `json:"result"`
  13. }
  14. func getapi(wallet string) ([]byte, error) {
  15. res, err := http.Get("https://api.bscscan.com/api?module=account&action=txlist&address=" + wallet + "&startblock=0&endblock=99999999&sort=asc&apikey=5Q4SS1XHV95SIPSCKK1FKCPGJSMRM2EI1K")
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. defer res.Body.Close()
  20. return ioutil.ReadAll(res.Body)
  21. }
  22. func j_unm(body []byte) Response {
  23. var r Response
  24. err := json.Unmarshal(body, &r)
  25. if err != nil {
  26. log.Println("Error unmarshalling json data:", err)
  27. }
  28. return r
  29. }
  30. func printitem(r Response, jitem string) []string {
  31. item := []string{}
  32. for _, p := range r.Result {
  33. item = append(item, jitem+":"+p[jitem])
  34. }
  35. return item
  36. }
  37. func main() {
  38. gettrx, _ := getapi("0xf287E9f40f96C0cbAEAdD29Cf22E6CF5cC66030b")
  39. fmt.Println(printitem(j_unm(gettrx), "blockNumber"))
  40. }

huangapple
  • 本文由 发表于 2022年7月25日 10:26:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73103496.html
匿名

发表评论

匿名网友

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

确定