go/json.go
Snider 8626710f9d feat: add JSON primitives + fix api.go placeholder
core.JSONMarshal(), JSONMarshalString(), JSONUnmarshal(), JSONUnmarshalString()
wrap encoding/json so consumers don't import it directly.
Same guardrail pattern as string.go wraps strings.

api.go Call() now uses JSONMarshalString instead of placeholder optionsToJSON.
7 AX-7 tests. 490 tests total, 84.8% coverage.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-25 17:40:55 +00:00

58 lines
1.4 KiB
Go

// SPDX-License-Identifier: EUPL-1.2
// JSON helpers for the Core framework.
// Wraps encoding/json so consumers don't import it directly.
// Same guardrail pattern as string.go wraps strings.
//
// Usage:
//
// data := core.JSONMarshal(myStruct)
// if data.OK { json := data.Value.([]byte) }
//
// r := core.JSONUnmarshal(jsonBytes, &target)
// if !r.OK { /* handle error */ }
package core
import "encoding/json"
// JSONMarshal serialises a value to JSON bytes.
//
// r := core.JSONMarshal(myStruct)
// if r.OK { data := r.Value.([]byte) }
func JSONMarshal(v any) Result {
data, err := json.Marshal(v)
if err != nil {
return Result{err, false}
}
return Result{data, true}
}
// JSONMarshalString serialises a value to a JSON string.
//
// s := core.JSONMarshalString(myStruct)
func JSONMarshalString(v any) string {
data, err := json.Marshal(v)
if err != nil {
return "{}"
}
return string(data)
}
// JSONUnmarshal deserialises JSON bytes into a target.
//
// var cfg Config
// r := core.JSONUnmarshal(data, &cfg)
func JSONUnmarshal(data []byte, target any) Result {
if err := json.Unmarshal(data, target); err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// JSONUnmarshalString deserialises a JSON string into a target.
//
// var cfg Config
// r := core.JSONUnmarshalString(`{"port":8080}`, &cfg)
func JSONUnmarshalString(s string, target any) Result {
return JSONUnmarshal([]byte(s), target)
}