JSON writes a JSON response. It also provides a generic response data fields picker if the "fields" query parameter is set. For example, if you are requesting `?fields=a,b` for `e.JSON(200, map[string]int{ "a":1, "b":2, "c":3 })`, it should result in a JSON response like: `{"a":1, "b": 2}`.
(status int, data any)
| 185 | // For example, if you are requesting `?fields=a,b` for `e.JSON(200, map[string]int{ "a":1, "b":2, "c":3 })`, |
| 186 | // it should result in a JSON response like: `{"a":1, "b": 2}`. |
| 187 | func (e *Event) JSON(status int, data any) error { |
| 188 | e.setResponseHeaderIfEmpty(headerContentType, "application/json") |
| 189 | e.Response.WriteHeader(status) |
| 190 | |
| 191 | rawFields := e.Request.URL.Query().Get(jsonFieldsParam) |
| 192 | |
| 193 | // error response or no fields to pick |
| 194 | if rawFields == "" || status < 200 || status > 299 { |
| 195 | return json.NewEncoder(e.Response).Encode(data) |
| 196 | } |
| 197 | |
| 198 | // pick only the requested fields |
| 199 | modified, err := picker.Pick(data, rawFields) |
| 200 | if err != nil { |
| 201 | return err |
| 202 | } |
| 203 | |
| 204 | return json.NewEncoder(e.Response).Encode(modified) |
| 205 | } |
| 206 | |
| 207 | // XML writes an XML response. |
| 208 | // It automatically prepends the generic [xml.Header] string to the response. |