jsonette/json_node.rs
1/*
2 * Copyright (c) 2026 DevEtte.
3 *
4 * This project is dual-licensed under both the MIT License and the
5 * Apache License, Version 2.0 (the "License"). You may not use this
6 * file except in compliance with one of these licenses.
7 *
8 * You may obtain a copy of the Licenses at:
9 * - MIT: https://opensource.org
10 * - Apache 2.0: http://apache.org
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19//! JsonNode types definition
20
21use crate::types::Span;
22
23/// A key-value pair in a JSON object. Used to represent objects as lists of pairs
24/// to preserve key ordering and stay FFI-friendly.
25#[derive(Debug, Clone, PartialEq)]
26pub struct KeyValuePair {
27 /// The key of the property.
28 pub key: String,
29 /// The associated JSON node value.
30 pub value: JsonNode,
31}
32
33/// The JSON value tree returned by a successful parse.
34/// Each variant carries the byte-offset range (Span) from the original source code
35/// for accurate syntax highlighting, navigation, and error reporting.
36#[derive(Debug, Clone, PartialEq)]
37pub enum JsonNode {
38 /// A JSON null value.
39 Null(Span),
40 /// A JSON boolean value (true or false).
41 Bool(bool, Span),
42 /// A JSON number, storing both its evaluated `f64` representation and
43 /// its original raw string for lossless round-trip formatting.
44 Number(f64, String, Span),
45 /// A JSON string value.
46 String(String, Span),
47 /// A JSON array value.
48 Array(Vec<JsonNode>, Span),
49 /// A JSON object value, represented as a list of key-value pairs to preserve insertion order.
50 Object(Vec<KeyValuePair>, Span),
51}
52
53impl JsonNode {
54 /// Returns the type of the JSON node as a string.
55 pub fn node_type(&self) -> String {
56 match self {
57 JsonNode::Null(_) => "null".to_string(),
58 JsonNode::Bool(_, _) => "bool".to_string(),
59 JsonNode::Number(_, _, _) => "number".to_string(),
60 JsonNode::String(_, _) => "string".to_string(),
61 JsonNode::Array(_, _) => "array".to_string(),
62 JsonNode::Object(_, _) => "object".to_string(),
63 }
64 }
65
66 /// Returns the span of the JSON node.
67 pub fn span(&self) -> Span {
68 match self {
69 JsonNode::Null(span) => span.clone(),
70 JsonNode::Bool(_, span) => span.clone(),
71 JsonNode::Number(_, _, span) => span.clone(),
72 JsonNode::String(_, span) => span.clone(),
73 JsonNode::Array(_, span) => span.clone(),
74 JsonNode::Object(_, span) => span.clone(),
75 }
76 }
77}