We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

JSON Report

We're almost done! Our web crawler now extracts rich data from every page and stores it efficiently in a map. Let's export it to JSON so it's easy to read and share.

For example, one page record in that map might look like this:

pages := map[string]PageData{
    "learnwebscraping.dev/practice/ecommerce/products/ashenfang-longsword-fan-1001": {
        URL:            "https://learnwebscraping.dev/practice/ecommerce/products/ashenfang-longsword-fan-1001/",
        Heading:        "Ashenfang Longsword",
        FirstParagraph: "A balanced battlefield blade with a smoldering fuller and leather-wrapped grip.",
        OutgoingLinks: []string{
            "https://learnwebscraping.dev/practice/ecommerce/",
            "https://learnwebscraping.dev/practice/ecommerce/categories/",
            "https://learnwebscraping.dev/practice/ecommerce/categories/longswords/",
        },
        ImageURLs: []string{"https://learnwebscraping.dev/images/catalog/longswords.svg"},
    },
}

We want to create a report.json file containing a sorted array of all page records.

Assignment

type PageData struct {
    URL            string   `json:"url"`
    Heading        string   `json:"heading"`
    FirstParagraph string   `json:"first_paragraph"`
    OutgoingLinks  []string `json:"outgoing_links"`
    ImageURLs      []string `json:"image_urls"`
}
import "encoding/json"
func writeJSONReport(pages map[string]PageData, filename string) error
    • Sort the map keys for deterministic output
    • Build a []PageData slice in sorted order
    • Marshal it with json.MarshalIndent using indent=2
    • Write the result to disk with os.WriteFile

Here are some tips:

  • Sort keys: sort.Strings(keys)
  • Marshal: data, err := json.MarshalIndent(sorted, "", " ")
  • Write: os.WriteFile(filename, data, 0644)
    • Call writeJSONReport(cfg.pages, "report.json") after crawling completes
    • Verify report.json is created after running the crawler
    • Check that it contains a valid JSON array of page objects

Run and submit the CLI tests.