JSON and Go

Consider this JSON payload, most likely delivered from a REST endpoint:

{
  "base": "stations",
  "clouds": {
    "all": 90
  },
  "cod": 200,
  "coord": {
    "lat": 38.94,
    "lon": -84.54
  },
  "dt": 1587688327,
  "id": 4295776,
  "main": {
    "feels_like": 282.83,
    "humidity": 87,
    "pressure": 1002,
    "temp": 285.57,
    "temp_max": 286.15,
    "temp_min": 284.82
  },
  "name": "Independence",
  "rain": {
    "1h": 0.25
  },
  "sys": {
    "country": "US",
    "id": 3729,
    "sunrise": 1587638973,
    "sunset": 1587687770,
    "type": 1
  },
  "timezone": -14400,
  "visibility": 16093,
  "weather": [
    {
      "description": "light rain",
      "icon": "10n",
      "id": 500,
      "main": "Rain"
    }
  ],
  "wind": {
    "deg": 100,
    "speed": 4.1
  }
}

Assume the above payload represents the current weather in your area. In practice there would be a rest endpoint that would return this data. For our purposes we can just use the file locally. Furthermore assume you are only interested in the rain amount for the last hour; a tiny subset of the data.

"rain": {
    "1h": 0.25
  },

The canonical Go way of parsing json is to create a Struct representing the JSON data and the marshalling into it. However, there are often times where we arent sure of the json schema and are really only interested in a subset of the payload. For these scenarios, the jsonparser pacakage is extremely helpful

For our example with the file locally we can easily read it into a variable then call the GetFloat method since our value is a float.

data, err := ioutil.ReadFile("./data/rain_data.json")
if err != nil {
  fmt.Printf("error %v", err)
}
val, err := jsonparser.GetFloat(data, "rain", "1h")
fmt.Printf("rain 1h: %f \n", val) // 0.25

The jsonparser package has methods for different data types, and it proves quite useful when you have to pluck arbitrary data from a json payload.

Cheers