Skip to content

Commit 5c8c284

Browse files
feat: add JSON concept exercise (marshal and unmarshal) (#88)
1 parent e36b2ec commit 5c8c284

3 files changed

Lines changed: 65 additions & 0 deletions

File tree

internal/exercises/catalog.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,14 @@ projects:
176176
test_regex: ".*"
177177
hints:
178178
- Implement an in-memory key-value store with basic CRUD operations and optional persistence.
179+
- slug: 36_json
180+
title: JSON
181+
test_regex: ".*"
182+
hints:
183+
- Use the encoding/json package to work with JSON data.
184+
- Implement MarshalPerson to convert a struct into JSON using json.Marshal.
185+
- Implement UnmarshalPerson to convert a JSON string into a struct using json.Unmarshal.
186+
- Handle and return errors properly in both functions.
179187

180188
- slug: 109_epoch
181189
title: "Epoch Conversion"
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package json
2+
3+
// Task:
4+
// Implement JSON encoding and decoding using Go's standard library.
5+
//
6+
// 1. Define a struct named Person with fields Name and Email.
7+
// 2. Implement MarshalPerson to convert a Person struct into JSON.
8+
// 3. Implement UnmarshalPerson to convert a JSON string into a Person struct.
9+
// 4. Handle and return errors properly in both functions.
10+
11+
type Person struct {
12+
Name string `json:"name"`
13+
Email string `json:"email"`
14+
}
15+
16+
// MarshalPerson should convert a Person struct to a JSON string.
17+
func MarshalPerson(p Person) (string, error) {
18+
return "", nil
19+
}
20+
21+
// UnmarshalPerson should convert a JSON string to a Person struct.
22+
func UnmarshalPerson(jsonStr string) (Person, error) {
23+
return Person{}, nil
24+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package json
2+
3+
import "testing"
4+
5+
func TestMarshalPerson(t *testing.T) {
6+
p := Person{Name: "golearn", Email: "golearn@example.com"}
7+
8+
jsonStr, err := MarshalPerson(p)
9+
if err != nil {
10+
t.Fatalf("Unexpected error: %v", err)
11+
}
12+
13+
expected := `{"name":"golearn","email":"golearn@example.com"}`
14+
if jsonStr != expected {
15+
t.Errorf("Expected %s, got %s", expected, jsonStr)
16+
}
17+
}
18+
19+
func TestUnmarshalPerson(t *testing.T) {
20+
jsonStr := `{"name":"golearn","email":"golearn@example.com"}`
21+
22+
p, err := UnmarshalPerson(jsonStr)
23+
if err != nil {
24+
t.Fatalf("Unexpected error: %v", err)
25+
}
26+
27+
if p.Name != "golearn" {
28+
t.Errorf("Expected name 'golearn', got %s", p.Name)
29+
}
30+
if p.Email != "golearn@example.com" {
31+
t.Errorf("Expected email 'golearn@example.com', got %s", p.Email)
32+
}
33+
}

0 commit comments

Comments
 (0)