|
| 1 | +// Copyright (c) 2019-2025 Provable Inc. |
| 2 | +// This file is part of the snarkOS library. |
| 3 | + |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at: |
| 7 | + |
| 8 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | + |
| 16 | +use snarkvm::prelude::{Network, Plaintext, Value}; |
| 17 | + |
| 18 | +use anyhow::Result; |
| 19 | + |
| 20 | +/// Convert a `Value` to JSON. |
| 21 | +/// `Value` implements Serialize by just calling `to_string()` on the value, which leads to Display |
| 22 | +/// output which (sometimes) looks like JSON but isn't. |
| 23 | +/// We produce actual JSON by calling `serde_json::to_value` on the inner object. |
| 24 | +pub(crate) fn value_to_json<N: Network>(mapping_value: Option<&Value<N>>) -> Result<serde_json::Value> { |
| 25 | + let json_value = if let Some(mapping_value) = mapping_value { |
| 26 | + match mapping_value { |
| 27 | + Value::Plaintext(plaintext) => match plaintext { |
| 28 | + Plaintext::Array(array, _) => serde_json::to_value(array)?, |
| 29 | + Plaintext::Struct(map, _) => serde_json::to_value(map)?, |
| 30 | + Plaintext::Literal(literal, _) => serde_json::to_value(literal)?, |
| 31 | + }, |
| 32 | + Value::Record(record) => serde_json::to_value(record)?, |
| 33 | + Value::Future(future) => serde_json::to_value(future)?, |
| 34 | + } |
| 35 | + } else { |
| 36 | + serde_json::Value::Object(Default::default()) |
| 37 | + }; |
| 38 | + |
| 39 | + Ok(json_value) |
| 40 | +} |
| 41 | + |
| 42 | +pub(crate) fn mapping_to_json<N: Network>(mapping_values: &[(Plaintext<N>, Value<N>)]) -> Result<serde_json::Value> { |
| 43 | + let mut json = serde_json::Map::new(); |
| 44 | + for (key, value) in mapping_values { |
| 45 | + let key = match key { |
| 46 | + // TODO: not sure if keys can be anything other than literals |
| 47 | + Plaintext::Array(array, _) => serde_json::to_string(&array)?, |
| 48 | + Plaintext::Struct(map, _) => serde_json::to_string(&map)?, |
| 49 | + // We can not use json here as it would cause the key to be escaped |
| 50 | + Plaintext::Literal(literal, _) => literal.to_string(), |
| 51 | + }; |
| 52 | + json.insert(key, value_to_json(Some(value))?); |
| 53 | + } |
| 54 | + |
| 55 | + Ok(serde_json::Value::Object(json)) |
| 56 | +} |
0 commit comments