Skip to content

Commit

Permalink
Merge pull request #840 from Mathieu-Lala/main
Browse files Browse the repository at this point in the history
Parse json within a script
  • Loading branch information
schungx committed Mar 4, 2024
2 parents dce0771 + 1091f29 commit 184427d
Show file tree
Hide file tree
Showing 3 changed files with 201 additions and 5 deletions.
13 changes: 10 additions & 3 deletions src/packages/lang_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,19 @@ mod core_functions {
///
/// print(m); // prints #{"a":1, "b":2, "c":3}
/// ```
#[cfg(not(feature = "no_index"))]
#[cfg(not(feature = "no_object"))]
#[cfg(feature = "metadata")]
#[rhai_fn(return_raw)]
pub fn parse_json(_ctx: NativeCallContext, json: &str) -> RhaiResultOf<Dynamic> {
serde_json::from_str(json).map_err(|err| err.to_string().into())
#[cfg(feature = "metadata")]
let out = serde_json::from_str(json).map_err(|err| err.to_string().into());

#[cfg(not(feature = "metadata"))]
let out = ctx

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / NoStdBuild (ubuntu-latest, --profile unix, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Check Formatting

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,debugging, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Check Wasm build (--target wasm32-wasi)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Check Wasm build (--target wasm32-unknown-unknown --no-default-features)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,serde, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Check Wasm build (--target wasm32-unknown-unknown --no-default-features --features wasm-bindgen)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,decimal, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,no_float,decimal, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,unicode-xid-ident, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,internals, stable, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (stable, windows-latest, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (stable, macos-latest, false)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (beta, ubuntu-latest, false, --features unstable)

cannot find value `ctx` in this scope

Check failure on line 182 in src/packages/lang_core.rs

View workflow job for this annotation

GitHub Actions / Build (nightly, ubuntu-latest, true, --features unstable)

cannot find value `ctx` in this scope
.engine()
.parse_json(json, true)
.map(|map_object| Dynamic::from(map_object));

out
}
}

Expand Down
4 changes: 2 additions & 2 deletions tests/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn test_eval_globals() {
r#"
const XYZ = 123;
fn foo() { global::XYZ }
fn foo() { global::XYZ }
{
eval("const XYZ = 42;");
}
Expand All @@ -110,7 +110,7 @@ fn test_eval_globals() {
r#"
const XYZ = 123;
fn foo() { global::XYZ }
fn foo() { global::XYZ }
eval("const XYZ = 42;");
Expand Down
189 changes: 189 additions & 0 deletions tests/parse_json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
use rhai::{Engine, ParseErrorType, Scope, INT};

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,metadata, stable, false)

unused imports: `INT`, `ParseErrorType`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,sync,serde,metadata,internals,debugging, stable,...

unused imports: `INT`, `ParseErrorType`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,no_float,serde,metadata,internals,debugging, sta...

unused imports: `INT`, `ParseErrorType`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,f32_float,serde,metadata,internals,debugging, st...

unused imports: `INT`, `ParseErrorType`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,no_custom_syntax,serde,metadata,internals,debugg...

unused imports: `INT`, `ParseErrorType`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --tests --features testing-environ,only_i32,serde,metadata,internals,debugg...

unused imports: `INT`, `ParseErrorType`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,no_index,serde,metadata,internals,debugging, sta...

unused import: `INT`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,no_function,serde,metadata,internals,debugging, ...

unused imports: `Engine`, `INT`, `ParseErrorType`, `Scope`

Check warning on line 1 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,sync,no_time,no_function,no_float,no_position,no...

unused imports: `Engine`, `INT`, `ParseErrorType`, `Scope`

#[cfg(not(feature = "metadata"))]
mod without_metadata {
use super::*;

#[test]
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_index"))]
#[cfg(not(feature = "no_object"))]
fn test_parse_json() {
let engine = Engine::new();
let mut scope = Scope::new();

let map = engine
.eval_with_scope::<rhai::Map>(
&mut scope,
r#"
parse_json("{\
\"name\": \"John Doe\",\
\"age\": 43,\
\"address\": {\
\"street\": \"10 Downing Street\",\
\"city\": \"London\"\
},\
\"phones\": [\
\"+44 1234567\",\
\"+44 2345678\"\
]\
}")
"#,
)
.unwrap();

assert_eq!(map.len(), 4);
assert_eq!(map["name"].clone().into_immutable_string().expect("name should exist"), "John Doe");
assert_eq!(map["age"].as_int().expect("age should exist"), 43);
assert_eq!(map["phones"].clone().into_typed_array::<String>().expect("phones should exist"), ["+44 1234567", "+44 2345678"]);

let address = map["address"].read_lock::<rhai::Map>().expect("address should exist");
assert_eq!(address["city"].clone().into_immutable_string().expect("address.city should exist"), "London");
assert_eq!(address["street"].clone().into_immutable_string().expect("address.street should exist"), "10 Downing Street");
}

#[test]
#[cfg(feature = "no_index")]
#[cfg(not(feature = "no_function"))]
fn test_parse_json_err_no_index() {
let engine = Engine::new();
let mut scope = Scope::new();

let err = engine
.eval_with_scope::<rhai::Dynamic>(
&mut scope,
r#"
parse_json("{\
\"v\": [\
1,\
2\
]\
}")
"#,
)
.unwrap_err();

assert!(matches!(err.as_ref(), rhai::EvalAltResult::ErrorParsing(
ParseErrorType::BadInput(LexError::UnexpectedInput(token)), pos)
if token == "[" && *pos == rhai::Position::new(1, 7)));
}

#[test]
#[cfg(feature = "no_object")]
#[cfg(not(feature = "no_function"))]
fn test_parse_json_err_no_object() {
let engine = Engine::new();
let mut scope = Scope::new();

let err = engine
.eval_with_scope::<rhai::Dynamic>(
&mut scope,
r#"
parse_json("{\
\"v\": {\
\"a\": 1,\
\"b\": 2,\
}\
}")
"#,
)
.unwrap_err();

assert!(matches!(err.as_ref(), rhai::EvalAltResult::ErrorFunctionNotFound(msg, pos)
if msg == "parse_json (&str | ImmutableString | String)" && *pos == rhai::Position::new(2, 13)));
}
}

#[cfg(feature = "metadata")]
mod with_metadata {
use super::*;

Check warning on line 99 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,sync,no_time,no_function,no_float,no_position,no...

unused import: `super::*`

#[test]
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_index"))]
#[cfg(not(feature = "no_object"))]
fn test_parse_json() {
let engine = Engine::new();
let mut scope = Scope::new();

let map = engine
.eval_with_scope::<rhai::Map>(
&mut scope,
r#"
parse_json("{\
\"name\": \"John Doe\",\
\"age\": 43,\
\"address\": {\
\"street\": \"10 Downing Street\",\
\"city\": \"London\"\
},\
\"phones\": [\
\"+44 1234567\",\
\"+44 2345678\"\
]\
}")
"#,
)
.unwrap();

assert_eq!(map.len(), 4);
assert_eq!(map["name"].clone().into_immutable_string().expect("name should exist"), "John Doe");
assert_eq!(map["age"].as_int().expect("age should exist"), 43);
assert_eq!(map["phones"].clone().into_typed_array::<String>().expect("phones should exist"), ["+44 1234567", "+44 2345678"]);

let address = map["address"].read_lock::<rhai::Map>().expect("address should exist");
assert_eq!(address["city"].clone().into_immutable_string().expect("address.city should exist"), "London");
assert_eq!(address["street"].clone().into_immutable_string().expect("address.street should exist"), "10 Downing Street");
}

#[test]
#[cfg(feature = "no_index")]
#[cfg(not(feature = "no_function"))]
fn test_parse_json_err_no_index() {
let engine = Engine::new();
let mut scope = Scope::new();

let err = engine
.eval_with_scope::<rhai::Dynamic>(
&mut scope,
r#"
parse_json("{\
\"v\": [\
1,\
2\
]\
}")
"#,
)
.unwrap_err();

assert!(matches!(err.as_ref(), rhai::EvalAltResult::ErrorParsing(
ParseErrorType::BadInput(LexError::UnexpectedInput(token)), pos)

Check failure on line 161 in tests/parse_json.rs

View workflow job for this annotation

GitHub Actions / Build (ubuntu-latest, --features testing-environ,no_index,serde,metadata,internals,debugging, sta...

failed to resolve: use of undeclared type `LexError`
if token == "[" && *pos == rhai::Position::new(1, 7)));
}

#[test]
#[cfg(feature = "no_object")]
#[cfg(not(feature = "no_function"))]
fn test_parse_json_err_no_object() {
let engine = Engine::new();
let mut scope = Scope::new();

let err = engine
.eval_with_scope::<rhai::Dynamic>(
&mut scope,
r#"
parse_json("{\
\"v\": {\
\"a\": 1,\
\"b\": 2,\
}\
}")
"#,
)
.unwrap_err();

assert!(matches!(err.as_ref(), rhai::EvalAltResult::ErrorFunctionNotFound(msg, pos)
if msg == "parse_json (&str | ImmutableString | String)" && *pos == rhai::Position::new(2, 13)));
}
}

0 comments on commit 184427d

Please sign in to comment.