rusty_v8/
json.rs

1// Copyright 2019-2021 the Deno authors. All rights reserved. MIT license.
2//! A JSON Parser and Stringifier.
3use crate::Context;
4use crate::HandleScope;
5use crate::Local;
6use crate::String;
7use crate::Value;
8
9extern "C" {
10  fn v8__JSON__Parse(
11    context: *const Context,
12    json_string: *const String,
13  ) -> *const Value;
14  fn v8__JSON__Stringify(
15    context: *const Context,
16    json_object: *const Value,
17  ) -> *const String;
18}
19
20/// Tries to parse the string `json_string` and returns it as value if
21/// successful.
22pub fn parse<'s>(
23  scope: &mut HandleScope<'s>,
24  json_string: Local<'_, String>,
25) -> Option<Local<'s, Value>> {
26  unsafe {
27    scope
28      .cast_local(|sd| v8__JSON__Parse(sd.get_current_context(), &*json_string))
29  }
30}
31
32/// Tries to stringify the JSON-serializable object `json_object` and returns
33/// it as string if successful.
34pub fn stringify<'s>(
35  scope: &mut HandleScope<'s>,
36  json_object: Local<'_, Value>,
37) -> Option<Local<'s, String>> {
38  unsafe {
39    scope.cast_local(|sd| {
40      v8__JSON__Stringify(sd.get_current_context(), &*json_object)
41    })
42  }
43}