napi-rs/examples/napi/src/serde.rs
Gabriel Francisco 3983be23f5
fix(napi): big numbers losing precision on serde_json::Value (#1538)
* fix(napi): big numbers losing precision on serde_json::Value

* fix(napi): add feature flags for bigint on number conversion

* chore(napi): change MAX_SAFE_INT to constant and convert big numbers to string when bigint is not available

* chore(napi): change how the check for safe integer range is made
2023-03-23 13:34:34 +08:00

38 lines
903 B
Rust

use napi::bindgen_prelude::*;
use serde_json::{Map, Value};
use std::fs;
#[napi(object)]
#[derive(Serialize, Deserialize, Debug)]
/// This is an interface for package.json
struct PackageJson {
pub name: String,
/// The version of the package
pub version: String,
pub dependencies: Option<Map<String, Value>>,
#[serde(rename = "devDependencies")]
pub dev_dependencies: Option<Map<String, Value>>,
}
#[napi]
fn read_package_json() -> Result<PackageJson> {
let raw = fs::read_to_string("package.json")?;
let p: PackageJson = serde_json::from_str(&raw)?;
Ok(p)
}
#[napi]
fn get_package_json_name(package_json: PackageJson) -> String {
package_json.name
}
#[napi]
fn test_serde_roundtrip(data: Value) -> Value {
data
}
#[napi]
fn test_serde_big_number_precision(number: String) -> Value {
let data = format!("{{\"number\":{}}}", number);
serde_json::from_str(&data).unwrap()
}