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

Add support for the reviver function to JSON.parse #410

Merged
merged 11 commits into from
Jun 1, 2020
52 changes: 50 additions & 2 deletions boa/src/builtins/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,67 @@ mod tests;
/// [spec]: https://tc39.es/ecma262/#sec-json.parse
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
// TODO: implement optional revever argument.
pub fn parse(_: &mut Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
pub fn parse(_: &mut Value, args: &[Value], interpreter: &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(Value::from(json)),
Ok(json) => {
let j = Value::from(json);
if args.len() > 1 {
match args.get(1) {
Some(callback) => {
if callback.is_function() {
let mut holder = Value::new_object(None);
holder.set_field(Value::from(""), j.clone());
walk(callback, interpreter, &mut holder, Value::from(""))
} else {
Ok(j)
}
}
_ => Ok(j),
}
} else {
Ok(j)
}
HalidOdat marked this conversation as resolved.
Show resolved Hide resolved
}
Err(err) => Err(Value::from(err.to_string())),
}
}

fn walk(
callback: &Value,
interpreter: &mut Interpreter,
holder: &mut Value,
key: Value,
) -> ResultValue {
let mut value = holder.get_field(key.clone());

if value.is_object() {
let obj = value.as_object();
if obj.is_some() {
let obj = obj.unwrap().clone();
for (key, _val) in obj.properties.iter() {
let v = walk(callback, interpreter, &mut value, Value::from(key.as_str()));
match v {
Ok(v) => {
if !v.is_undefined() {
value.set_field(Value::from(key.as_str()), v);
} else {
value.remove_property(key.as_str());
}
}
Err(_v) => {}
}
}
}
}
HalidOdat marked this conversation as resolved.
Show resolved Hide resolved
interpreter.call(callback, holder, &[key, value])
}

/// `JSON.stringify( value[, replacer[, space]] )`
///
/// This `JSON` method converts a JavaScript object or value to a JSON string.
Expand Down