git.delta.rocks / jrsonnet / refs/commits / ff3e2c836938

difftreelog

source

crates/jrsonnet-stdlib/src/parse.rs1.0 KiBsourcehistory
1use jrsonnet_evaluator::{2	error::{Error::RuntimeError, Result},3	function::builtin,4	typed::{Any, Typed},5	IStr, State, Val,6};7use serde::Deserialize;89#[builtin]10pub fn builtin_parse_json(st: State, s: IStr) -> Result<Any> {11	use serde_json::Value;12	let value: Value = serde_json::from_str(&s)13		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;14	Ok(Any(Value::into_untyped(value, st)?))15}1617#[builtin]18pub fn builtin_parse_yaml(st: State, s: IStr) -> Result<Any> {19	use serde_json::Value;20	use serde_yaml_with_quirks::DeserializingQuirks;21	let value = serde_yaml_with_quirks::Deserializer::from_str_with_quirks(22		&s,23		DeserializingQuirks { old_octals: true },24	);25	let mut out = vec![];26	for item in value {27		let value = Value::deserialize(item)28			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;29		let val = Value::into_untyped(value, st.clone())?;30		out.push(val);31	}32	Ok(Any(if out.is_empty() {33		Val::Null34	} else if out.len() == 1 {35		out.into_iter().next().unwrap()36	} else {37		Val::Arr(out.into())38	}))39}