arrow_json/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Transfer data between the Arrow memory format and JSON line-delimited records.
19//!
20//! See the module level documentation for the
21//! [`reader`] and [`writer`] for usage examples.
22//!
23//! # Binary Data
24//!
25//! As per [RFC7159] JSON cannot encode arbitrary binary data. A common approach to workaround
26//! this is to use a [binary-to-text encoding] scheme, such as base64, to encode the
27//! input data and then decode it on output.
28//!
29//! ```
30//! # use std::io::Cursor;
31//! # use std::sync::Arc;
32//! # use arrow_array::{BinaryArray, RecordBatch, StringArray};
33//! # use arrow_array::cast::AsArray;
34//! # use arrow_cast::base64::{b64_decode, b64_encode, BASE64_STANDARD};
35//! # use arrow_json::{LineDelimitedWriter, ReaderBuilder};
36//! #
37//! // The data we want to write
38//! let input = BinaryArray::from(vec![b"\xDE\x00\xFF".as_ref()]);
39//!
40//! // Base64 encode it to a string
41//! let encoded: StringArray = b64_encode(&BASE64_STANDARD, &input);
42//!
43//! // Write the StringArray to JSON
44//! let batch = RecordBatch::try_from_iter([("col", Arc::new(encoded) as _)]).unwrap();
45//! let mut buf = Vec::with_capacity(1024);
46//! let mut writer = LineDelimitedWriter::new(&mut buf);
47//! writer.write(&batch).unwrap();
48//! writer.finish().unwrap();
49//!
50//! // Read the JSON data
51//! let cursor = Cursor::new(buf);
52//! let mut reader = ReaderBuilder::new(batch.schema()).build(cursor).unwrap();
53//! let batch = reader.next().unwrap().unwrap();
54//!
55//! // Reverse the base64 encoding
56//! let col: BinaryArray = batch.column(0).as_string::<i32>().clone().into();
57//! let output = b64_decode(&BASE64_STANDARD, &col).unwrap();
58//!
59//! assert_eq!(input, output);
60//! ```
61//!
62//! [RFC7159]: https://datatracker.ietf.org/doc/html/rfc7159#section-8.1
63//! [binary-to-text encoding]: https://en.wikipedia.org/wiki/Binary-to-text_encoding
64//!
65
66#![deny(rustdoc::broken_intra_doc_links)]
67#![warn(missing_docs)]
68
69pub mod reader;
70pub mod writer;
71
72pub use self::reader::{Reader, ReaderBuilder};
73pub use self::writer::{ArrayWriter, LineDelimitedWriter, Writer, WriterBuilder};
74use half::f16;
75use serde_json::{Number, Value};
76
77/// Specifies what is considered valid JSON when reading or writing
78/// RecordBatches or StructArrays.
79///
80/// This enum controls which form(s) the Reader will accept and which form the
81/// Writer will produce. For example, if the RecordBatch Schema is
82/// `[("a", Int32), ("r", Struct([("b", Boolean), ("c", Utf8)]))]`
83/// then a Reader with [`StructMode::ObjectOnly`] would read rows of the form
84/// `{"a": 1, "r": {"b": true, "c": "cat"}}` while with ['StructMode::ListOnly']
85/// would read rows of the form `[1, [true, "cat"]]`. A Writer would produce
86/// rows formatted similarly.
87///
88/// The list encoding is more compact if the schema is known, and is used by
89/// tools such as [Presto] and [Trino].
90///
91/// When reading objects, the order of the key does not matter. When reading
92/// lists, the entries must be the same number and in the same order as the
93/// struct fields. Map columns are not affected by this option.
94///
95/// [Presto]: (https://prestodb.io/docs/current/develop/client-protocol.html#important-queryresults-attributes)
96/// [Trino]: (https://trino.io/docs/current/develop/client-protocol.html#important-queryresults-attributes)
97#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
98pub enum StructMode {
99    #[default]
100    /// Encode/decode structs as objects (e.g., {"a": 1, "b": "c"})
101    ObjectOnly,
102    /// Encode/decode structs as lists (e.g., [1, "c"])
103    ListOnly,
104}
105
106/// Trait declaring any type that is serializable to JSON. This includes all primitive types (bool, i32, etc.).
107pub trait JsonSerializable: 'static {
108    /// Converts self into json value if its possible
109    fn into_json_value(self) -> Option<Value>;
110}
111
112macro_rules! json_serializable {
113    ($t:ty) => {
114        impl JsonSerializable for $t {
115            fn into_json_value(self) -> Option<Value> {
116                Some(self.into())
117            }
118        }
119    };
120}
121
122json_serializable!(bool);
123json_serializable!(u8);
124json_serializable!(u16);
125json_serializable!(u32);
126json_serializable!(u64);
127json_serializable!(i8);
128json_serializable!(i16);
129json_serializable!(i32);
130json_serializable!(i64);
131
132impl JsonSerializable for i128 {
133    fn into_json_value(self) -> Option<Value> {
134        // Serialize as string to avoid issues with arbitrary_precision serde_json feature
135        // - https://github.com/serde-rs/json/issues/559
136        // - https://github.com/serde-rs/json/issues/845
137        // - https://github.com/serde-rs/json/issues/846
138        Some(self.to_string().into())
139    }
140}
141
142impl JsonSerializable for f16 {
143    fn into_json_value(self) -> Option<Value> {
144        Number::from_f64(f64::round(f64::from(self) * 1000.0) / 1000.0).map(Value::Number)
145    }
146}
147
148impl JsonSerializable for f32 {
149    fn into_json_value(self) -> Option<Value> {
150        Number::from_f64(f64::round(self as f64 * 1000.0) / 1000.0).map(Value::Number)
151    }
152}
153
154impl JsonSerializable for f64 {
155    fn into_json_value(self) -> Option<Value> {
156        Number::from_f64(self).map(Value::Number)
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    use serde_json::Value::{Bool, Number as VNumber, String as VString};
165
166    #[test]
167    fn test_arrow_native_type_to_json() {
168        assert_eq!(Some(Bool(true)), true.into_json_value());
169        assert_eq!(Some(VNumber(Number::from(1))), 1i8.into_json_value());
170        assert_eq!(Some(VNumber(Number::from(1))), 1i16.into_json_value());
171        assert_eq!(Some(VNumber(Number::from(1))), 1i32.into_json_value());
172        assert_eq!(Some(VNumber(Number::from(1))), 1i64.into_json_value());
173        assert_eq!(Some(VString("1".to_string())), 1i128.into_json_value());
174        assert_eq!(Some(VNumber(Number::from(1))), 1u8.into_json_value());
175        assert_eq!(Some(VNumber(Number::from(1))), 1u16.into_json_value());
176        assert_eq!(Some(VNumber(Number::from(1))), 1u32.into_json_value());
177        assert_eq!(Some(VNumber(Number::from(1))), 1u64.into_json_value());
178        assert_eq!(
179            Some(VNumber(Number::from_f64(0.01f64).unwrap())),
180            0.01.into_json_value()
181        );
182        assert_eq!(
183            Some(VNumber(Number::from_f64(0.01f64).unwrap())),
184            0.01f64.into_json_value()
185        );
186        assert_eq!(None, f32::NAN.into_json_value());
187    }
188
189    #[test]
190    fn test_json_roundtrip_structs() {
191        use crate::writer::LineDelimited;
192        use arrow_schema::DataType;
193        use arrow_schema::Field;
194        use arrow_schema::Fields;
195        use arrow_schema::Schema;
196        use std::sync::Arc;
197
198        let schema = Arc::new(Schema::new(vec![
199            Field::new(
200                "c1",
201                DataType::Struct(Fields::from(vec![
202                    Field::new("c11", DataType::Int32, true),
203                    Field::new(
204                        "c12",
205                        DataType::Struct(vec![Field::new("c121", DataType::Utf8, false)].into()),
206                        false,
207                    ),
208                ])),
209                false,
210            ),
211            Field::new("c2", DataType::Utf8, false),
212        ]));
213
214        {
215            let object_input = r#"{"c1":{"c11":1,"c12":{"c121":"e"}},"c2":"a"}
216{"c1":{"c12":{"c121":"f"}},"c2":"b"}
217{"c1":{"c11":5,"c12":{"c121":"g"}},"c2":"c"}
218"#
219            .as_bytes();
220            let object_reader = ReaderBuilder::new(schema.clone())
221                .with_struct_mode(StructMode::ObjectOnly)
222                .build(object_input)
223                .unwrap();
224
225            let mut object_output: Vec<u8> = Vec::new();
226            let mut object_writer = WriterBuilder::new()
227                .with_struct_mode(StructMode::ObjectOnly)
228                .build::<_, LineDelimited>(&mut object_output);
229            for batch_res in object_reader {
230                object_writer.write(&batch_res.unwrap()).unwrap();
231            }
232            assert_eq!(object_input, &object_output);
233        }
234
235        {
236            let list_input = r#"[[1,["e"]],"a"]
237[[null,["f"]],"b"]
238[[5,["g"]],"c"]
239"#
240            .as_bytes();
241            let list_reader = ReaderBuilder::new(schema.clone())
242                .with_struct_mode(StructMode::ListOnly)
243                .build(list_input)
244                .unwrap();
245
246            let mut list_output: Vec<u8> = Vec::new();
247            let mut list_writer = WriterBuilder::new()
248                .with_struct_mode(StructMode::ListOnly)
249                .build::<_, LineDelimited>(&mut list_output);
250            for batch_res in list_reader {
251                list_writer.write(&batch_res.unwrap()).unwrap();
252            }
253            assert_eq!(list_input, &list_output);
254        }
255    }
256}