0

Trying to parse a JSON object via Go and iterate through the records and print selected fields only. Facing issue as unable to reference while printing using fmt.

JSON Object Structure:

type myBalanceInfo struct {
     Name     string                    `json:"name"`
     Id       int64                     `json:"id"`
     Balances map[string]myBalance      `json:"balances"`
}
type myBalance[]myBalanceInfo

type myBalance struct {
     Available decimal.Decimal          `json:"available"`
     Balance   decimal.Decimal          `json:"balance"`
 }

temp.json:

 {
"abc": {
    "name": "abc",
    "id": 1,
    "balances": {
        "acc1": {
            "available": "1.2",
            "balance": "1.2"
        },
        "acc2": {
            "available": "2.000001",
            "balance": "2.000001"
        },
        "acc3": {
            "available": "0.000001",
            "balance": "0.000001"
        },
        "acc4": {
            "available": "1000",
            "balance": "1000"
        }
    }
}

}

Main:

jsonInputFile := os.Open("temp.json")
defer jsonInputFile.Close()

jsonByteValue, _ := ioutil.ReadAll(jsonInputFile )
var data []myBalanceInfo
json.Unmarshal([]byte(jsonByteValue), &data )

for i := 0; i < (len(data)); i++ {
    fmt.Println("ID: " + strconv.FormatInt(data[i].Id, 10))
    fmt.Println("Balance: " + decimal.NewFromString(data[i].Balance))
}

Error:

Invalid operation: "Balance: " + walletData[i].Balance (mismatched types string and decimal.Decimal)"

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Lastwish
  • 317
  • 10
  • 21

1 Answers1

0

Replace this line

fmt.Println("Balance: " + decimal.NewFromString(data[i].Balance))

with

fmt.Println("Balance: " , data[i].Balance)

Because,

func NewFromString(value string) (Decimal, error)

Take string as an argument and return Decimal with error. While the value you are passing is already a Decimal.

One more thing the "+" sign in

fmt.Println("Balance: " + decimal.NewFromString(data[i].Balance))

Assume that the value returned by decimal.NewFromString(data[i].Balance) will be string which is not. that is why you are getting error.

Invalid operation: "Balance: " + walletData[i].Balance (mismatched types string and decimal.Decimal)"

Umar Hayat
  • 4,300
  • 1
  • 12
  • 27