Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse json within a script #840

Merged
merged 6 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@
///
/// 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 / Build (nightly, ubuntu-latest, true, --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 (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 (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 (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 (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 / 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 (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 (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 (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 / 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 / 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 / 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 / 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 / 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 Formatting

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
@@ -1,4 +1,4 @@
use rhai::{Engine, LexError, ParseErrorType, Scope, INT};

Check warning on line 1 in tests/eval.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: `Scope`

#[test]
fn test_eval() {
Expand Down Expand Up @@ -92,7 +92,7 @@
r#"
const XYZ = 123;

fn foo() { global::XYZ }
fn foo() { global::XYZ }
{
eval("const XYZ = 42;");
}
Expand All @@ -110,7 +110,7 @@
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,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_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, --features testing-environ,no_time,serde,metadata,internals,debugging, stab...

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,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,only_i64,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,no_optimize,serde,metadata,internals,debugging, ...

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,unchecked,serde,metadata,internals,debugging, st...

unused imports: `INT`, `ParseErrorType`

#[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,no_function,serde,metadata,internals,debugging, ...

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)
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)));
}
}