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

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

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

问题

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

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

import "reflect"

func printitem(r Response, jitem string) []string {
	item := []string{}
	for _, p := range r.Result {
		value := reflect.ValueOf(p)
		field := reflect.Indirect(value).FieldByName(jitem)
		if field.IsValid() {
			item = append(item, jitem+":"+field.String())
		}
	}
	return item
}

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

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

英文:
package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
)

type Response struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Result  []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"`
	} `json:"result"`
}

func getapi(wallet string) ([]byte, error) {
	res, err := http.Get("https://api.bscscan.com/api?module=account&action=txlist&address=" + wallet + "&startblock=0&endblock=99999999&sort=asc&apikey=5Q4SS1XHV95SIPSCKK1FKCPGJSMRM2EI1K")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	return ioutil.ReadAll(res.Body)
}

func j_unm(body []byte) Response {
	var r Response
	err := json.Unmarshal(body, &r)
	if err != nil {
		log.Println("Error unmarshalling json data:", err)
	}
	return r
}

func printitem(r Response, jitem string) []string {
	item := []string{}
	for _, p := range r.Result {
		item = append(item, jitem+":"+p.jitem)
	}
	return item
}


package main


import "fmt"

func main() {
	gettrx, _ := getapi("0xf287E9f40f96C0cbAEAdD29Cf22E6CF5cC66030b")
	fmt.Println(printitem(j_unm(gettrx), "BlockNumber"))
}

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)

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

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

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

答案2

得分: 0

你想要这个吗?

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

type Response struct {
	Status  string              `json:"status"`
	Message string              `json:"message"`
	Result  []map[string]string `json:"result"`
}

func getapi(wallet string) ([]byte, error) {
	res, err := http.Get("https://api.bscscan.com/api?module=account&action=txlist&address=" + wallet + "&startblock=0&endblock=99999999&sort=asc&apikey=5Q4SS1XHV95SIPSCKK1FKCPGJSMRM2EI1K")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	return ioutil.ReadAll(res.Body)
}

func j_unm(body []byte) Response {
	var r Response
	err := json.Unmarshal(body, &r)
	if err != nil {
		log.Println("Error unmarshalling json data:", err)
	}
	return r
}

func printitem(r Response, jitem string) []string {
	item := []string{}
	for _, p := range r.Result {
		item = append(item, jitem+":"+p[jitem])
	}
	return item
}

func main() {
	gettrx, _ := getapi("0xf287E9f40f96C0cbAEAdD29Cf22E6CF5cC66030b")
	fmt.Println(printitem(j_unm(gettrx), "blockNumber"))
}

英文:

do you want this?

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

type Response struct {
	Status  string              `json:"status"`
	Message string              `json:"message"`
	Result  []map[string]string `json:"result"`
}

func getapi(wallet string) ([]byte, error) {
	res, err := http.Get("https://api.bscscan.com/api?module=account&action=txlist&address=" + wallet + "&startblock=0&endblock=99999999&sort=asc&apikey=5Q4SS1XHV95SIPSCKK1FKCPGJSMRM2EI1K")
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	return ioutil.ReadAll(res.Body)
}

func j_unm(body []byte) Response {
	var r Response
	err := json.Unmarshal(body, &r)
	if err != nil {
		log.Println("Error unmarshalling json data:", err)
	}
	return r
}

func printitem(r Response, jitem string) []string {
	item := []string{}
	for _, p := range r.Result {
		item = append(item, jitem+":"+p[jitem])
	}
	return item
}

func main() {
	gettrx, _ := getapi("0xf287E9f40f96C0cbAEAdD29Cf22E6CF5cC66030b")
	fmt.Println(printitem(j_unm(gettrx), "blockNumber"))
}

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:

确定