nemo_flow/json.rs
1// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! JSON utilities for the NeMo Flow runtime.
5//!
6//! This module provides a [`Json`] type alias for [`serde_json::Value`] used
7//! throughout the crate, and a [`merge_json`] helper for shallow-merging
8//! optional JSON values.
9
10/// Type alias for [`serde_json::Value`], used as the universal JSON
11/// representation throughout the NeMo Flow runtime.
12pub type Json = serde_json::Value;
13
14/// Shallow-merge two optional JSON values.
15///
16/// This is used throughout the runtime to combine optional `data` and
17/// `metadata` payloads without recursively descending into nested objects.
18///
19/// # Parameters
20/// - `a`: Base JSON value.
21/// - `b`: Override JSON value.
22///
23/// # Returns
24/// An [`Option`] containing the merged JSON value. When both inputs are JSON
25/// objects, keys from `b` override keys from `a`. When only one input is
26/// present, that input is returned. When both inputs are present but at least
27/// one is not an object, `b` wins.
28///
29/// # Notes
30/// The merge is shallow. Nested objects are replaced rather than merged
31/// recursively.
32pub fn merge_json(a: Option<Json>, b: Option<Json>) -> Option<Json> {
33 match (a, b) {
34 (Some(Json::Object(mut ma)), Some(Json::Object(mb))) => {
35 for (k, v) in mb {
36 ma.insert(k, v);
37 }
38 Some(Json::Object(ma))
39 }
40 (Some(a), None) => Some(a),
41 (None, Some(b)) => Some(b),
42 (Some(_), Some(b)) => Some(b),
43 (None, None) => None,
44 }
45}
46
47#[cfg(test)]
48#[path = "../tests/unit/json_tests.rs"]
49mod tests;