Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions internal/exercises/catalog.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ concepts:
test_regex: ".*"
hints:
- Define a custom error type and return it from a function.
- slug: json
title: JSON
test_regex: ".*"
hints:
- Use the encoding/json package to work with JSON data.
- Implement MarshalPerson to convert a struct into JSON using json.Marshal.
- Implement UnmarshalPerson to convert a JSON string into a struct using json.Unmarshal.
- Handle and return errors properly in both functions.
Comment thread
sidharth-chauhan marked this conversation as resolved.
Outdated

projects:
- slug: 28_text_analyzer
Expand Down
24 changes: 24 additions & 0 deletions internal/exercises/templates/36_json/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package json

// Task:
// Implement JSON encoding and decoding using Go's standard library.
//
// 1. Define a struct named Person with fields Name and Email.
// 2. Implement MarshalPerson to convert a Person struct into JSON.
// 3. Implement UnmarshalPerson to convert a JSON string into a Person struct.
// 4. Handle and return errors properly in both functions.

type Person struct {
Name string `json:"name"`
Email string `json:"email"`
}

// MarshalPerson should convert a Person struct to a JSON string.
func MarshalPerson(p Person) (string, error) {
return "", nil
}

// UnmarshalPerson should convert a JSON string to a Person struct.
func UnmarshalPerson(jsonStr string) (Person, error) {
return Person{}, nil
}
33 changes: 33 additions & 0 deletions internal/exercises/templates/36_json/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package json

import "testing"

func TestMarshalPerson(t *testing.T) {
p := Person{Name: "golearn", Email: "golearn@example.com"}

jsonStr, err := MarshalPerson(p)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

expected := `{"name":"golearn","email":"golearn@example.com"}`
if jsonStr != expected {
t.Errorf("Expected %s, got %s", expected, jsonStr)
}
}

func TestUnmarshalPerson(t *testing.T) {
jsonStr := `{"name":"golearn","email":"golearn@example.com"}`

p, err := UnmarshalPerson(jsonStr)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

if p.Name != "golearn" {
t.Errorf("Expected name 'golearn', got %s", p.Name)
}
if p.Email != "golearn@example.com" {
t.Errorf("Expected email 'golearn@example.com', got %s", p.Email)
}
}