AzLearn

تمرين إعادة البناء

JSON Contacts

أعد كتابة برنامج Go يقرأ جهات اتصال من JSON.

go ~18 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
package main

import (
	"encoding/json"
	"fmt"
	"sort"
)

type Contact struct {
	Name  string `json:"name"`
	Phone string `json:"phone"`
	City  string `json:"city"`
}

func contactsByCity(data []byte, city string) ([]Contact, error) {
	var contacts []Contact
	if err := json.Unmarshal(data, &contacts); err != nil {
		return nil, err
	}

	var matches []Contact
	for _, contact := range contacts {
		if contact.City == city {
			matches = append(matches, contact)
		}
	}
	sort.Slice(matches, func(i, j int) bool {
		return matches[i].Name < matches[j].Name
	})
	return matches, nil
}

func main() {
	data := []byte(`[
  {"name":"Amina","phone":"0551111111","city":"Riyadh"},
  {"name":"Omar","phone":"0552222222","city":"Jeddah"},
  {"name":"Noura","phone":"0553333333","city":"Riyadh"}
]`)

	contacts, err := contactsByCity(data, "Riyadh")
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	for _, contact := range contacts {
		fmt.Printf("%s: %s\n", contact.Name, contact.Phone)
	}
}
اكتب هنا