First two values from json object using std template package

Issue

The json response from api is like this

{
  "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"
    }
  ]
}

I am trying to write a golang template which returns only the first two data points in data section of the response object. This is the template {{range $element := .data}} {{$element}} {{end}} i am using at the moment but this returns all the sub data in .data feild. How can i make this workout.

Solution

You can use the slice template function to take the first two elements. Example:

{{$dataSliced := slice .data 0 2}}
{{range $element := $dataSliced}}
    {{$element}}
{{end}}

Or you can also create a custom template function for the slicing.

More about template function: https://golang.org/pkg/text/template.

Answered By – novalagung

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.