I have problem how to print a variable for, in outside for, in Go? I'm using library GJSON gjson
I have try many way , I just entered the global variable but just appear final index, like:
datePriodGlobal = DatePeriod.String()
and
datePriodGlobal = DatePeriod.String()
another way I try but appear just final index too, like below:
tempPayments:= "Envelope.Body.GetCustomReportResponse.GetCustomReportResult.ContractSummary.PaymentCalendarList.PaymentCalendar."
resultMapPriodTest := gjson.Get(jsonString,tempPayments + "#.Date")
resultContractsSubmittedTest := gjson.Get(jsonString, tempPayments + "#.ContractsSubmitted")
var datePriodGlobal string
for _, DatePeriod := range resultMapPriodTest.Array()[1:13] {
datePriodGlobal = fmt.Sprintf("%s", DatePeriod.String())
}
var contractsSubmittedGlobal string
for _, ContractsSubmitted := range resultContractsSubmittedTest.Array()[1:13]{
contractsSubmittedGlobal = fmt.Sprintf("%s", ContractsSubmitted.String())
}
fmt.Printf("%s | %s \t|",datePriodGlobal, contractsSubmittedGlobal)
}
I have json like this:
"Cannot use 'DatePeriod' (type Result) as type string in assignment"
So, the variable DatePeriod
is a Result
type, not a String
. You're specifying you want to print a string with %s
, but not giving fmt.Sprintf
a string, causing that error. The Sprintf
is unnecessary if the value given was already a String
.
Looking at gjson.go, the Result
type has a String()
method, so you'd want instead DatePeriod.String()
.
EDIT:
From your latest edit, I think I see your second issue. Your loops replace the ...Global
string variables each time, so you'll only ever get the last value in the slice you've passed to range
. Since your slices are identical in length, you might be better off with something like this:
resultMapPriodTest := gjson.Get(jsonString,tempPayments + "#.Date")
resultContractsSubmittedTest := gjson.Get(jsonString, tempPayments + "#.ContractsSubmitted")
dateArray := resultMapPriodTest.Array()[1:13]
contractsArray := resultContractsSubmittedTest.Array()[1:13]
for i := 0; i<len(dateArray); i++ {
d := dateArray[i].String()
c := contractsArray[i].String()
fmt.Printf("%s | %s \t|", d, c)
}
I will suggest just iterate over the PaymentCalendar
as a slice of JSON objects rather than querying each field using the indexes as their pseudo-ids.
Here is a simple demonstration:
func main() {
jsonString := `
{
"PaymentCalendarList": {
"PaymentCalendar": [
{"ContractSubmitted": 10,
"Date": "2018-01-01T01:01:01"},
{"ContractSubmitted": 20,
"Date": "2018-01-01T02:02:02"},
{"ContractSubmitted": 30,
"Date": "2018-01-01T03:03:03"}
{"ContractSubmitted": 40,
"Date": "2018-01-01T04:04:04"}
{"ContractSubmitted": 50,
"Date": "2018-01-01T05:05:05"}
]
}
}`
result := gjson.Get(jsonString, "PaymentCalendarList.PaymentCalendar")
for _, paymentCal := range result.Array()[0:3] {
date := paymentCal.Get("Date")
contractSubmit := paymentCal.Get("ContractSubmitted")
fmt.Printf("%s | %s
", date, contractSubmit)
}
}