api的json响应是这样的
{
"ResponseCode": "1",
"Response": "Data Found",
"data": [
{
"Season": "KHARIF",
"Sector": "AGRICULTURE",
"Category": "Cereals",
"Crop": "Paddy (Dhan)",
"QueryType": "\tField Preparation\t",
"QueryText": "top dressing for paddy",
"KccAns": "top dressing for paddy : apply urea 25kg+SSP 15kg + neem cake 5kg+MN mixture 5kg mixed with 40kg of sand",
"StateName": "PUDUCHERRY",
"DistrictName": "KARAIKAL",
"BlockName": "KARAIKAL",
"CreatedOn": "1/5/2014 6:48:09 PM"
},
{
"Season": "KHARIF",
"Sector": "AGRICULTURE",
"Category": "Others",
"Crop": "Others",
"QueryType": "Weather",
"QueryText": "weather forecasting details",
"KccAns": "today no rain",
"StateName": "PUDUCHERRY",
"DistrictName": "KARAIKAL",
"BlockName": "KARAIKAL",
"CreatedOn": "1/5/2014 9:04:50 PM"
},
{
"Season": "KHARIF",
"Sector": "AGRICULTURE",
"Category": "Others",
"Crop": "Others",
"QueryType": "0",
"QueryText": "details about soil testing",
"KccAns": "contact to agricultural department",
"StateName": "PUDUCHERRY",
"DistrictName": "KARAIKAL",
"BlockName": "KARAIKAL",
"CreatedOn": "1/8/2014 10:21:18 AM"
},
{
"Season": "KHARIF",
"Sector": "AGRICULTURE",
"Category": "Cereals",
"Crop": "Paddy (Dhan)",
"QueryType": "Fertilizer Use and Availability",
"QueryText": "paddy top dressing fertilizer",
"KccAns": "apply urea 25 kg + potash 15 kg + neem cake 5 kg + microfood 5 kg / ac",
"StateName": "PUDUCHERRY",
"DistrictName": "KARAIKAL",
"BlockName": "KARAIKAL",
"CreatedOn": "1/12/2014 8:01:45 AM"
}
]
}
我正在尝试编写一个golang模板,该模板仅返回响应对象的data部分中的前两个数据点。这是我目前正在使用的模板
{{range $element := .data}} {{$element}} {{end}}
,但这将返回.data领域中的所有子数据。我该如何做这个锻炼。 最佳答案
如果您的go版本至少为go1.13,则可以使用slice
模板函数获取前两个元素。例:
{{$dataSliced := slice .data 0 2}}
{{range $element := $dataSliced}}
{{$element}}
{{end}}
对于旧版本的go,可以通过使用
range
和if lt
关键字获得相同的结果。例:{{range $index, $element := .data}}
{{if lt $index 2}}
{{$element}}
{{end}}
{{end}}
或者,您也可以为 slice 创建自定义模板功能。
有关模板功能的更多信息:https://golang.org/pkg/text/template。