setAtPath puts a JSON value at a dotted path inside a JSON body. Numeric segments index arrays. Missing objects along the way are created.
(body json.RawMessage, path, value string)
| 367 | // setAtPath puts a JSON value at a dotted path inside a JSON body. Numeric |
| 368 | // segments index arrays. Missing objects along the way are created. |
| 369 | func setAtPath(body json.RawMessage, path, value string) (json.RawMessage, error) { |
| 370 | var root any = map[string]any{} |
| 371 | if len(bytes.TrimSpace(body)) > 0 { |
| 372 | if err := decodeJSON(body, &root); err != nil { |
| 373 | return nil, fmt.Errorf("current body is not valid JSON: %w", err) |
| 374 | } |
| 375 | } |
| 376 | var val any |
| 377 | if err := decodeJSON([]byte(value), &val); err != nil { |
| 378 | return nil, fmt.Errorf("--json is not valid JSON: %w", err) |
| 379 | } |
| 380 | segments := strings.Split(path, ".") |
| 381 | if slices.Contains(segments, "") { |
| 382 | return nil, fmt.Errorf("--at %q has an empty segment", path) |
| 383 | } |
| 384 | root, err := setPath(root, segments, val, "") |
| 385 | if err != nil { |
| 386 | return nil, err |
| 387 | } |
| 388 | return json.Marshal(root) |
| 389 | } |
| 390 | |
| 391 | func setPath(node any, segments []string, val any, walked string) (any, error) { |
| 392 | if len(segments) == 0 { |
no test coverage detected