Crates.io | json_size |
lib.rs | json_size |
version | 0.1.3 |
source | src |
created_at | 2024-05-10 11:34:20.250625 |
updated_at | 2024-05-15 17:34:36.584409 |
description | A crate to calculate the size of a JSON object |
homepage | |
repository | https://github.com/dariaag/json_size |
max_upload_size | |
id | 1235927 |
size | 8,496 |
sizeof_val
is a Rust function that calculates an approximate size of a serde_json::Value
in bytes. It estimates the memory consumption of various types of JSON data and their nested structures.
Original code
Add the following dependencies to your Cargo.toml
file:
[dependencies]
serde = "1.0"
serde_json = "1.0"
To use the sizeof_val
function, follow these steps:
Import the necessary modules:
use serde_json::{Value, json};
Define the sizeof_val
function:
use serde_json::Value;
use std::mem::size_of;
pub fn sizeof_val(v: &serde_json::Value) -> usize {
size_of::<serde_json::Value>()
+ match v {
Value::Null => 0,
Value::Bool(_) => 0,
Value::Number(_) => 0, // incorrect if arbitrary_precision is enabled
Value::String(s) => s.capacity(),
Value::Array(a) => a.iter().map(sizeof_val).sum(),
Value::Object(o) => o
.iter()
.map(|(k, v)| {
size_of::<String>() + k.capacity() + sizeof_val(v) + size_of::<usize>() * 3
//crude approximation, each map entry has 3 words of overhead
})
.sum(),
}
}
Use the function to estimate the size of a JSON value:
fn main() {
let val = json!({
"name": "OpenAI",
"founded": 2015,
"services": ["chatbot", "API"]
});
let size = sizeof_val(&val);
println!("Estimated size: {} bytes", size);
}
The following example demonstrates the use of the sizeof_val
function:
use serde_json::{Value, json};
fn main() {
let val = json!({
"name": "bread",
"amount": 2,
});
let size = sizeof_val(&val);
println!("Estimated size: {} bytes", size);
}
serde_json
crate.Feel free to submit pull requests or open issues for any improvements or bugs related to the sizeof_val
function.
This project is licensed under the MIT License.