Skip to main content

v8/
json.rs

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