dongtang4954 2018-11-21 13:37
浏览 42
已采纳

如何在golang中为外部打印变量?

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:

enter image description here

  • 写回答

2条回答 默认 最新

  • drxrgundk062317205 2018-11-21 13:55
    关注

    "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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?