Browse Source

added JSON

pull/5/head
Jason Williams 6 years ago
parent
commit
ae7e5277b2
  1. 28
      src/lib/js/json.rs
  2. 2
      src/lib/js/value.rs

28
src/lib/js/json.rs

@ -1,35 +1,33 @@
use js::function::Function;
/// The JSON Object /// The JSON Object
/// https://tc39.github.io/ecma262/#sec-json-object /// https://tc39.github.io/ecma262/#sec-json-object
use gc::GcCell; use js::value::{to_value, ResultValue, Value};
use js::value::{to_value, ResultValue, Value, ValueData}; use serde_json::{self, to_string_pretty, Value as JSONValue};
use serde_json;
/// Parse a JSON string into a Javascript object /// Parse a JSON string into a Javascript object
/// https://tc39.github.io/ecma262/#sec-json.parse /// https://tc39.github.io/ecma262/#sec-json.parse
pub fn parse(args: Vec<Value>) -> ResultValue { pub fn parse(args: Vec<Value>, _: Value, _: Value, _: Value) -> ResultValue {
match serde_json::from_str(&args.get(0).unwrap().clone().to_string()) { match serde_json::from_str::<JSONValue>(&args.get(0).unwrap().clone().to_string()) {
Ok(json) => Ok(to_value(json)), Ok(json) => Ok(to_value(json)),
Err(err) => Err(to_value(err.to_string())), Err(err) => Err(to_value(err.to_string())),
} }
} }
/// Process a Javascript object into a JSON string /// Process a Javascript object into a JSON string
pub fn stringify(args: Vec<Value>) -> ResultValue { pub fn stringify(args: Vec<Value>, _: Value, _: Value, _: Value) -> ResultValue {
let obj = args.get(0); let obj = args.get(0).unwrap();
let json = serde_json::to_string_pretty(obj.clone()).unwrap(); let json = obj.to_json();
Ok(to_value(json.to_pretty_str())) Ok(to_value(to_string_pretty(&json).unwrap()))
} }
/// Create a new `JSON` object /// Create a new `JSON` object
pub fn _create(global: Value) -> Value { pub fn _create(global: Value) -> Value {
let object = ValueData::new_obj(Some(global)); let object = Value::new_obj(Some(global));
let object_ptr = object.borrow(); object.set_field_slice("stringify", Function::make(stringify, &["JSON"]));
object_ptr.set_field_slice("stringify", to_value(stringify)); object.set_field_slice("parse", Function::make(parse, &["JSON_string"]));
object_ptr.set_field_slice("parse", to_value(parse));
object object
} }
/// Initialise the global object with the `JSON` object /// Initialise the global object with the `JSON` object
pub fn init(global: Value) { pub fn init(global: Value) {
let global_ptr = global.borrow(); global.set_field_slice("JSON", _create(global.clone()));
global_ptr.set_field_slice("JSON", _create(global));
} }

2
src/lib/js/value.rs

@ -257,7 +257,7 @@ impl Value {
} }
} }
fn to_json(&self) -> JSONValue { pub fn to_json(&self) -> JSONValue {
match *self.ptr { match *self.ptr {
ValueData::Null | ValueData::Undefined => JSONValue::Null, ValueData::Null | ValueData::Undefined => JSONValue::Null,
ValueData::Boolean(b) => JSONValue::Bool(b), ValueData::Boolean(b) => JSONValue::Bool(b),

Loading…
Cancel
Save