From e1f3eca2b5f50a4ff9c65309f5f2dd1d568f432c Mon Sep 17 00:00:00 2001 From: Christian Simon Date: Sat, 15 May 2021 17:39:50 +0000 Subject: [PATCH] feat(evaluator): adds std.parseJson builtin method --- --- 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 { + 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 { parse_args!(context, "slice", args, 4, [ --- a/crates/jrsonnet-evaluator/src/lib.rs +++ b/crates/jrsonnet-evaluator/src/lib.rs @@ -802,6 +802,21 @@ } #[test] + fn parse_json() { + assert_json!( + r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#, + r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"# + ); + // TODO: this should in fact fail as is no proper JSON syntax + assert_json!( + r#"std.parseJson("{a:-1, b:1, c:3.141, d:[]}")"#, + r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"# + ); + // TODO: this is also no valid JSON + assert_json!(r#"std.parseJson('local x = 2; x * x')"#, r#"4"#); + } + + #[test] fn test() { assert_json!( r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#, -- gitstuff