Skip to content

Commit

Permalink
json stringify "whitelist" replacer
Browse files Browse the repository at this point in the history
  • Loading branch information
n14little committed May 14, 2020
1 parent 402041d commit 167e6d6
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
37 changes: 34 additions & 3 deletions boa/src/builtins/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@
//! [json]: https://www.json.org/json-en.html
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

use crate::builtins::value::{ResultValue, Value};
use crate::builtins::{
value::{ResultValue, Value, ValueData},
object::ObjectKind
};
use crate::exec::Interpreter;
use std::ops::Deref;
use serde_json::{self, Value as JSONValue};

#[cfg(test)]
Expand Down Expand Up @@ -63,8 +67,35 @@ pub fn parse(_: &mut Value, args: &[Value], _: &mut Interpreter) -> ResultValue
/// [spec]: https://tc39.es/ecma262/#sec-json.stringify
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
pub fn stringify(_: &mut Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
let obj = args.get(0).expect("cannot get argument for JSON.stringify");
let json = obj.to_json().to_string();
let object = args.get(0).expect("cannot get argument for JSON.stringify");
let object_to_return = Value::new_object(None);
if let Some(arg) = args.get(1) {
match arg.data() {
ValueData::Object(ref obj) => {
let derefed_obj = (*obj).deref();
let borrowed_derefed_obj = derefed_obj.borrow();
if borrowed_derefed_obj.kind == ObjectKind::Array {
for (key, value) in borrowed_derefed_obj.properties.iter() {
if let Some(Value(x)) = &value.value {
if key != "length" {
object_to_return.set_property(
x.to_string(),
object.get_property(&x.to_string()).unwrap()
);
}
}
}
return Ok(Value::from(object_to_return.to_json().to_string()));
} else {
panic!("replacer only supports arrays at this time");
}
}
_ => {
panic!("replacer only supports arrays at this time");
}
}
}
let json = object.to_json().to_string();
Ok(Value::from(json))
}

Expand Down
18 changes: 18 additions & 0 deletions boa/src/builtins/json/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,21 @@ fn json_sanity() {
"true"
);
}

#[test]
fn json_stringify_replacer_array() {
let realm = Realm::create();
let mut engine = Executor::new(realm);
let actual = forward(
&mut engine,
r#"JSON.stringify({aaa: 'bbb', bbb: 'ccc', ccc: 'ddd'}, ['aaa', 'bbb'])"#
);
let expected = forward(
&mut engine,
r#"'{"aaa":"bbb","bbb":"ccc"}'"#
);
assert_eq!(
actual,
expected
);
}

0 comments on commit 167e6d6

Please sign in to comment.