Print a json item wit a for loop

63 views
Skip to first unread message

Alexis Gavidia

unread,
Jul 24, 2022, 11:37:21 PM7/24/22
to golang-nuts
Please help me with this


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

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

Brian Candler

unread,
Jul 25, 2022, 4:03:11 AM7/25/22
to golang-nuts
You haven't said what you're trying to do, and the error tells you that p doesn't have a field called "jitem".

Perhaps what you are trying to do is to extract a member from a structure dynamically: that is, jitem is the *name* of a struct member, only known at runtime?  In that case, you can use the Reflect package:

But that's really ugly and I think you should avoid it if at all possible.  Go is not Python.

There are safer and simpler approaches, for example:

If all you're trying to do is pretty-print JSON, then encoding/json can do that for you:
or you can use a YAML library.
Reply all
Reply to author
Forward
0 new messages