1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use crate::builtins::function::NativeFunctionData;
use crate::builtins::object::{Object, ObjectKind, PROTOTYPE};
use crate::builtins::value::{to_value, ResultValue, Value, ValueData};
use crate::exec::Interpreter;
use serde_json::{self, to_string_pretty, Value as JSONValue};
pub fn parse(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
match serde_json::from_str::<JSONValue>(
&args
.get(0)
.expect("cannot get argument for JSON.parse")
.clone()
.to_string(),
) {
Ok(json) => Ok(to_value(json)),
Err(err) => Err(to_value(err.to_string())),
}
}
pub fn stringify(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
let obj = args.get(0).expect("cannot get argument for JSON.stringify");
let json = obj.to_json();
Ok(to_value(to_string_pretty(&json).expect("")))
}
pub fn create_constructor(global: &Value) -> Value {
let mut json = Object::default();
json.kind = ObjectKind::Ordinary;
let prototype = ValueData::new_obj(Some(global));
make_builtin_fn!(parse, named "parse", with length 2, of prototype);
make_builtin_fn!(stringify, named "stringify", with length 3, of prototype);
let json_value = to_value(json);
json_value.set_field_slice(PROTOTYPE, prototype);
json_value
}