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

difftreelog

feat(evaluator) adds std.parseJson builtin method

Christian Simon2021-05-18parent: #0be1df1.patch.diff
in: master

2 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,8 +1,8 @@
 use crate::{
 	equals,
 	error::{Error::*, Result},
-	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, FuncVal, LazyVal,
-	Val,
+	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, EvaluationState,
+	FuncVal, LazyVal, Val,
 };
 use format::{format_arr, format_obj};
 use jrsonnet_interner::IStr;
@@ -74,6 +74,7 @@
 			("reverse".into(), builtin_reverse),
 			("id".into(), builtin_id),
 			("strReplace".into(), builtin_str_replace),
+			("parseJson".into(), builtin_parse_json),
 		].iter().cloned().collect()
 	};
 }
@@ -164,6 +165,20 @@
 	})
 }
 
+fn builtin_parse_json(
+	context: Context,
+	_loc: Option<&ExprLocation>,
+	args: &ArgsDesc,
+) -> Result<Val> {
+	parse_args!(context, "parseJson", args, 1, [
+		0, s: ty!(string) => Val::Str;
+	], {
+		let state = EvaluationState::default();
+		let path = Rc::new(PathBuf::from("std.parseJson"));
+		state.evaluate_snippet_raw(path ,s)
+	})
+}
+
 // faster
 fn builtin_slice(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
 	parse_args!(context, "slice", args, 4, [
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
801 );801 );
802 }802 }
803
804 #[test]
805 fn parse_json() {
806 assert_json!(
807 r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,
808 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#
809 );
810 // TODO: this should in fact fail as is no proper JSON syntax
811 assert_json!(
812 r#"std.parseJson("{a:-1, b:1, c:3.141, d:[]}")"#,
813 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#
814 );
815 // TODO: this is also no valid JSON
816 assert_json!(r#"std.parseJson('local x = 2; x * x')"#, r#"4"#);
817 }
803818
804 #[test]819 #[test]
805 fn test() {820 fn test() {