Add parse_json.

This commit is contained in:
Stephen Chung
2022-09-29 22:46:59 +08:00
parent 6c777e68d3
commit e8fd965eba
9 changed files with 78 additions and 34 deletions

View File

@@ -88,7 +88,6 @@ mod core_functions {
#[cfg(feature = "f32_float")]
std::thread::sleep(std::time::Duration::from_secs_f32(seconds));
}
/// Block the current thread for a particular number of `seconds`.
#[cfg(not(feature = "no_std"))]
pub fn sleep(seconds: INT) {
@@ -97,6 +96,23 @@ mod core_functions {
}
std::thread::sleep(std::time::Duration::from_secs(seconds as u64));
}
/// Parse a JSON string into a value.
///
/// # Example
///
/// ```rhai
/// let m = parse_json(`{"a":1, "b":2, "c":3}`);
///
/// 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(not(feature = "no_function"))]

View File

@@ -2,7 +2,7 @@
use crate::engine::OP_EQUALS;
use crate::plugin::*;
use crate::{def_package, format_map_as_json, Dynamic, ImmutableString, Map, RhaiResultOf, INT};
use crate::{def_package, Dynamic, ImmutableString, Map, NativeCallContext, RhaiResultOf, INT};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
@@ -304,6 +304,9 @@ mod map_functions {
/// print(m.to_json()); // prints {"a":1, "b":2, "c":3}
/// ```
pub fn to_json(map: &mut Map) -> String {
format_map_as_json(map)
#[cfg(feature = "metadata")]
return serde_json::to_string(map).unwrap_or_else(|_| "ERROR".into());
#[cfg(not(feature = "metadata"))]
return crate::format_map_as_json(map);
}
}