go
45 lines · 7 steps
Parsing untyped JSON config in Go
How to safely walk a dynamic JSON blob and build a map of service URLs using type assertions.
Explained by
highlit
1package config
2
3import (
4 "encoding/json"
5 "fmt"
6)
7
8func ExtractServiceEndpoints(raw []byte) (map[string]string, error) {
9 var doc map[string]interface{}
10 if err := json.Unmarshal(raw, &doc); err != nil {
11 return nil, fmt.Errorf("invalid config json: %w", err)
12 }
13
14 services, ok := doc["services"].(map[string]interface{})
15 if !ok {
16 return nil, fmt.Errorf("missing or malformed 'services' object")
17 }
18
19 endpoints := make(map[string]string, len(services))
20 for name, entry := range services {
21 cfg, ok := entry.(map[string]interface{})
22 if !ok {
23 continue
24 }
25
26 host, _ := cfg["host"].(string)
27 if host == "" {
28 return nil, fmt.Errorf("service %q has no host", name)
29 }
30
31 port := 80
32 if p, ok := cfg["port"].(float64); ok {
33 port = int(p)
34 }
35
36 scheme := "http"
37 if tls, ok := cfg["tls"].(bool); ok && tls {
38 scheme = "https"
39 }
40
41 endpoints[name] = fmt.Sprintf("%s://%s:%d", scheme, host, port)
42 }
43
44 return endpoints, nil
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Unmarshaling into map[string]interface{} lets you handle JSON whose shape you don't know at compile time.
- 2Comma-ok type assertions turn risky casts into safe branches you can validate or default.
- 3JSON numbers always decode to float64 in Go, so numeric fields need an explicit conversion.
Related explainers
go
package main import ( "net/http"
How route groups nest in Gin
routing
middleware
api versioning
Intermediate
6 steps
ruby
class FundsTransfer class InsufficientFundsError < StandardError; end def initialize(source:, destination:, amount:)
Atomic money transfers with Rails transactions
service object
database transactions
row locking
Advanced
9 steps
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
javascript
const express = require('express'); const v1 = express.Router();
Versioning an API with Express Routers
api versioning
routing
modularity
Intermediate
10 steps
go
package cache import ( "container/list"
Building a generic LRU cache in Go
lru-cache
generics
linked-list
Intermediate
8 steps
go
package model import ( "encoding/json"
Custom JSON marshaling in Go
json
serialization
interfaces
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-untyped-json-config-in-go-explained-go-1ee4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.