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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址