Go · Level 3 JSON

Decoding JSON

Decode a JSON request body into typed Go structs with json.Unmarshal and total the order, avoiding map[string]any, where every number turns into a float64.

  • json.Unmarshal(data, &v) fills a struct
  • nested structs and slices decode too
  • in any, numbers are float64

json.Unmarshal(data, &v) fills a struct from JSON, matching keys by tag. Trap: decoded into any or map[string]any, every number becomes a float64, and v.(int) panics. Decode into a typed struct instead.

var m map[string]any
json.Unmarshal([]byte(`{"qty":2}`), &m)
_, isInt := m["qty"].(int)    // false
_, isF := m["qty"].(float64)  // true

Write OrderTotal(body string) (int, error): decode a body like {"items":[{"price":120,"qty":2}]} and return the sum of price × qty, or 0 and the error if the JSON is invalid. Example: that body → 240, nil.

solution.go
Test Suites Pending
Output