| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame^] | 1 | // Copyright The Monogon Project Authors. |
| Lorenz Brun | f042e6f | 2020-06-24 16:46:09 +0200 | [diff] [blame] | 2 | // SPDX-License-Identifier: Apache-2.0 |
| Lorenz Brun | f042e6f | 2020-06-24 16:46:09 +0200 | [diff] [blame] | 3 | |
| Serge Bazanski | 216fe7b | 2021-05-21 18:36:16 +0200 | [diff] [blame] | 4 | // Package jsonpatch contains data structures and encoders for JSON Patch (RFC |
| 5 | // 6902) and JSON Pointers (RFC 6901) |
| Lorenz Brun | f042e6f | 2020-06-24 16:46:09 +0200 | [diff] [blame] | 6 | package jsonpatch |
| 7 | |
| 8 | import "strings" |
| 9 | |
| Tim Windelschmidt | 8732d43 | 2024-04-18 23:20:05 +0200 | [diff] [blame] | 10 | // JsonPatchOp describes a JSON Patch operation (RFC 6902 Section 4) |
| Lorenz Brun | f042e6f | 2020-06-24 16:46:09 +0200 | [diff] [blame] | 11 | type JsonPatchOp struct { |
| 12 | Operation string `json:"op"` |
| 13 | Path string `json:"path"` // Technically a JSON Pointer, but called Path in the RFC |
| 14 | From string `json:"from,omitempty"` |
| 15 | Value interface{} `json:"value,omitempty"` |
| 16 | } |
| 17 | |
| Serge Bazanski | 216fe7b | 2021-05-21 18:36:16 +0200 | [diff] [blame] | 18 | // EncodeJSONRefToken encodes a JSON reference token as part of a JSON Pointer |
| 19 | // (RFC 6901 Section 2) |
| Lorenz Brun | f042e6f | 2020-06-24 16:46:09 +0200 | [diff] [blame] | 20 | func EncodeJSONRefToken(token string) string { |
| 21 | x := strings.ReplaceAll(token, "~", "~0") |
| 22 | return strings.ReplaceAll(x, "/", "~1") |
| 23 | } |
| 24 | |
| 25 | // PointerFromParts returns an encoded JSON Pointer from parts |
| 26 | func PointerFromParts(pathParts []string) string { |
| 27 | var encodedParts []string |
| 28 | encodedParts = append(encodedParts, "") |
| 29 | for _, part := range pathParts { |
| 30 | encodedParts = append(encodedParts, EncodeJSONRefToken(part)) |
| 31 | } |
| 32 | return strings.Join(encodedParts, "/") |
| 33 | } |