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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器