Bài tập: Tổng hợp đơn hàng JSON
Input là một mảng JSON đơn hàng:
[{"id":1,"customer":"an","amount":120},{"id":2,"customer":"binh","amount":50},{"id":3,"customer":"an","amount":30}]- Khai báo struct
Ordervới struct tag phù hợp. - Viết
func totalsByCustomer(data []byte) (map[string]int, error)cộngamounttheocustomer. - JSON sai cú pháp hoặc sai kiểu (không phải mảng,
amountlà chuỗi…) → trả lỗi; driver sẽ ininvalid input.
Khóa thừa (ví dụ "note") phải được bỏ qua. Output (đã có sẵn) in customer total sắp theo tên:
an 150
binh 50NOTE
Bạn chỉ viết phần code trong khung soạn thảo — package main, hàm main đọc input/in kết quả đã có sẵn. Các package đã import: encoding/json, fmt, io, os, sort. Không thêm import khác.
Examples
Example 1
Input
[{"id":1,"customer":"an","amount":120},{"id":2,"customer":"binh","amount":50},{"id":3,"customer":"an","amount":30}]
Expected output
an 150 binh 50
Example 2
Input
{"id": 1}
Expected output
invalid input
3 hidden tests · Limit 2 s · 256 MB
type Order struct {
// TODO: thêm field với struct tag json
}
// totalsByCustomer giải mã mảng JSON các đơn hàng và cộng amount theo customer.
func totalsByCustomer(data []byte) (map[string]int, error) {
// TODO
return nil, nil
}
Comments