mirror of https://github.com/boa-dev/boa.git
Jason Williams
6 years ago
2 changed files with 14 additions and 16 deletions
@ -1,35 +1,33 @@
|
||||
use js::function::Function; |
||||
/// The JSON Object
|
||||
/// https://tc39.github.io/ecma262/#sec-json-object
|
||||
use gc::GcCell; |
||||
use js::value::{to_value, ResultValue, Value, ValueData}; |
||||
use serde_json; |
||||
use js::value::{to_value, ResultValue, Value}; |
||||
use serde_json::{self, to_string_pretty, Value as JSONValue}; |
||||
|
||||
/// Parse a JSON string into a Javascript object
|
||||
/// https://tc39.github.io/ecma262/#sec-json.parse
|
||||
pub fn parse(args: Vec<Value>) -> ResultValue { |
||||
match serde_json::from_str(&args.get(0).unwrap().clone().to_string()) { |
||||
pub fn parse(args: Vec<Value>, _: Value, _: Value, _: Value) -> ResultValue { |
||||
match serde_json::from_str::<JSONValue>(&args.get(0).unwrap().clone().to_string()) { |
||||
Ok(json) => Ok(to_value(json)), |
||||
Err(err) => Err(to_value(err.to_string())), |
||||
} |
||||
} |
||||
/// Process a Javascript object into a JSON string
|
||||
pub fn stringify(args: Vec<Value>) -> ResultValue { |
||||
let obj = args.get(0); |
||||
let json = serde_json::to_string_pretty(obj.clone()).unwrap(); |
||||
Ok(to_value(json.to_pretty_str())) |
||||
pub fn stringify(args: Vec<Value>, _: Value, _: Value, _: Value) -> ResultValue { |
||||
let obj = args.get(0).unwrap(); |
||||
let json = obj.to_json(); |
||||
Ok(to_value(to_string_pretty(&json).unwrap())) |
||||
} |
||||
|
||||
/// Create a new `JSON` object
|
||||
pub fn _create(global: Value) -> Value { |
||||
let object = ValueData::new_obj(Some(global)); |
||||
let object_ptr = object.borrow(); |
||||
object_ptr.set_field_slice("stringify", to_value(stringify)); |
||||
object_ptr.set_field_slice("parse", to_value(parse)); |
||||
let object = Value::new_obj(Some(global)); |
||||
object.set_field_slice("stringify", Function::make(stringify, &["JSON"])); |
||||
object.set_field_slice("parse", Function::make(parse, &["JSON_string"])); |
||||
object |
||||
} |
||||
|
||||
/// Initialise the global object with the `JSON` object
|
||||
pub fn init(global: Value) { |
||||
let global_ptr = global.borrow(); |
||||
global_ptr.set_field_slice("JSON", _create(global)); |
||||
global.set_field_slice("JSON", _create(global.clone())); |
||||
} |
||||
|
Loading…
Reference in new issue