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 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势