Skip to content

Commit bd19a62

Browse files
authored
Add example of converting RecordBatches to JSON objects (#5364)
* Add example of converting RecordBatches to JSON objects * twea * Update docs * Use from_reader and simplify example
1 parent 0dda129 commit bd19a62

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

arrow-json/src/writer.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,36 @@
7474
//! [`LineDelimitedWriter`] and [`ArrayWriter`] will omit writing keys with null values.
7575
//! In order to explicitly write null values for keys, configure a custom [`Writer`] by
7676
//! using a [`WriterBuilder`] to construct a [`Writer`].
77-
77+
//!
78+
//! ## Writing to [serde_json] JSON Objects
79+
//!
80+
//! To serialize [`RecordBatch`]es into an array of
81+
//! [JSON](https://docs.serde.rs/serde_json/) objects you can reparse the resulting JSON string.
82+
//! Note that this is less efficient than using the `Writer` API.
83+
//!
84+
//! ```
85+
//! # use std::sync::Arc;
86+
//! # use arrow_array::{Int32Array, RecordBatch};
87+
//! # use arrow_schema::{DataType, Field, Schema};
88+
//! let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
89+
//! let a = Int32Array::from(vec![1, 2, 3]);
90+
//! let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
91+
//!
92+
//! // Write the record batch out as json bytes (string)
93+
//! let buf = Vec::new();
94+
//! let mut writer = arrow_json::ArrayWriter::new(buf);
95+
//! writer.write_batches(&vec![&batch]).unwrap();
96+
//! writer.finish().unwrap();
97+
//! let json_data = writer.into_inner();
98+
//!
99+
//! // Parse the string using serde_json
100+
//! use serde_json::{Map, Value};
101+
//! let json_rows: Vec<Map<String, Value>> = serde_json::from_reader(json_data.as_slice()).unwrap();
102+
//! assert_eq!(
103+
//! serde_json::Value::Object(json_rows[1].clone()),
104+
//! serde_json::json!({"a": 2}),
105+
//! );
106+
//! ```
78107
mod encoder;
79108

80109
use std::iter;

0 commit comments

Comments
 (0)