This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new 82366f7832 feat(json): add opt-in non-finite float parsing to JSON
reader (#11725)
82366f7832 is described below
commit 82366f7832fb88f01d21b604245aa0bb8c717e3e
Author: dentiny <[email protected]>
AuthorDate: Thu Nov 5 06:57:28 2026 +0000
feat(json): add opt-in non-finite float parsing to JSON reader (#11725)
# Which issue does this PR close?
Closes https://github.com/apache/arrow-rs/issues/11724
# Rationale for this change
Some JSON/JSONL datasets contain bare NaN, Infinity, and -Infinity
values. Arrow’s floating-point types can represent these values, but the
JSON tokenizer currently rejects them because they are outside the
standard JSON grammar—even when the supplied schema specifies
floating-point columns.
Supporting these literals through an explicit opt-in improves
interoperability with existing datasets. Users can read them directly
without preprocessing entire files or maintaining a separate parser,
while preserving nonfinite numeric values rather than converting them to
null, which represents missing data. Keeping this behavior disabled by
default preserves compatibility for users who require strict JSON
parsing.
# What changes are included in this PR?
This PR adds an option for JSON reader to accept non-infinite floating
points, it's default off to keep the current behavior.
The same behavior and option also exist in other json reader:
https://ibireme.github.io/yyjson/doc/doxygen/html/yyjson_8h.html#a4b5c0a7092625f0324bccec938f8862f
# Are these changes tested?
Yes
# Are there any significant user-facing changes?
No
---
arrow-json/src/reader/mod.rs | 52 +++++++++++++++++++++++++++++++++++++++++++
arrow-json/src/reader/tape.rs | 45 +++++++++++++++++++++++++++++++++----
2 files changed, 93 insertions(+), 4 deletions(-)
diff --git a/arrow-json/src/reader/mod.rs b/arrow-json/src/reader/mod.rs
index e01e9bac60..50310a338f 100644
--- a/arrow-json/src/reader/mod.rs
+++ b/arrow-json/src/reader/mod.rs
@@ -195,6 +195,7 @@ pub struct ReaderBuilder {
coerce_primitive: bool,
strict_mode: bool,
ignore_type_conflicts: bool,
+ allow_non_finite_floats: bool,
is_field: bool,
struct_mode: StructMode,
flatten_top_level_arrays: bool,
@@ -217,6 +218,7 @@ impl ReaderBuilder {
coerce_primitive: false,
strict_mode: false,
ignore_type_conflicts: false,
+ allow_non_finite_floats: false,
is_field: false,
struct_mode: Default::default(),
flatten_top_level_arrays: false,
@@ -261,6 +263,7 @@ impl ReaderBuilder {
coerce_primitive: false,
strict_mode: false,
ignore_type_conflicts: false,
+ allow_non_finite_floats: false,
is_field: true,
struct_mode: Default::default(),
flatten_top_level_arrays: false,
@@ -283,6 +286,18 @@ impl ReaderBuilder {
}
}
+ /// Accepts the nonstandard number literals `NaN`, `Infinity`, and
`-Infinity`.
+ ///
+ /// Disabled by default. Floating-point columns preserve their IEEE values;
+ /// other types follow the existing coercion and type-conflict options.
+ /// Applies to known-schema readers only, not schema inference.
+ pub fn with_allow_non_finite_floats(self, allow_non_finite_floats: bool)
-> Self {
+ Self {
+ allow_non_finite_floats,
+ ..self
+ }
+ }
+
/// Sets if the decoder should return an error if it encounters a column
not
/// present in `schema`. If `struct_mode` is `ListOnly` the value of
/// `strict_mode` is effectively `true`. It is required for all fields of
@@ -393,6 +408,7 @@ impl ReaderBuilder {
batch_size: self.batch_size,
num_fields,
flatten_top_level_arrays: self.flatten_top_level_arrays,
+ allow_non_finite_floats: self.allow_non_finite_floats,
}),
batch_size: self.batch_size,
schema: self.schema,
@@ -4503,4 +4519,40 @@ mod tests {
let err = read(false);
assert!(err.contains("returned 0 values for 1 rows"), "{err}");
}
+
+ #[test]
+ fn test_non_finite_floats() {
+ let schema = infer_json_schema_from_iterator(std::iter::once(Ok(json!({
+ "metadata": {"year": 0.0}, "values": [0.0], "text": ""
+ }))))
+ .unwrap();
+ let builder = ReaderBuilder::new(Arc::new(schema));
+ let input =
r#"{"metadata":{"year":NaN},"values":[Infinity,-Infinity,null],"text":"NaN
\"Infinity\""}"#;
+ let mut reader = builder.clone().build(input.as_bytes()).unwrap();
+ assert!(reader.next().unwrap().is_err());
+
+ // Existing helper covers small I/O buffers and multiple batch sizes.
+ let builder = builder.with_allow_non_finite_floats(true);
+ let batches = do_read_config(&format!("{input}\n{input}"),
builder.clone());
+ let batch = &batches[0];
+ let year = batch
+ .column_by_name("metadata")
+ .unwrap()
+ .as_struct()
+ .column_by_name("year")
+ .unwrap()
+ .as_primitive::<Float64Type>();
+ assert_eq!(year.null_count(), 0);
+ assert!(year.values().iter().all(|value| value.is_nan()));
+ let lists = batch.column_by_name("values").unwrap().as_list::<i32>();
+ let text = batch.column_by_name("text").unwrap().as_string::<i32>();
+ for row in 0..batch.num_rows() {
+ let values = lists.value(row);
+ let values = values.as_primitive::<Float64Type>();
+ assert_eq!(values.value(0), f64::INFINITY);
+ assert_eq!(values.value(1), f64::NEG_INFINITY);
+ assert!(values.is_null(2));
+ assert_eq!(text.value(row), r#"NaN "Infinity""#);
+ }
+ }
}
diff --git a/arrow-json/src/reader/tape.rs b/arrow-json/src/reader/tape.rs
index 7729212dc4..e0ccec6f1d 100644
--- a/arrow-json/src/reader/tape.rs
+++ b/arrow-json/src/reader/tape.rs
@@ -238,7 +238,7 @@ enum DecoderState {
///
/// Consists of a `(low surrogate, high surrogate, decoded length)`
Unicode(u16, u16, u8),
- /// A boolean or null literal
+ /// A boolean, null, or enabled nonfinite number literal
///
/// Consists of `(literal, decoded length)`
Literal(Literal, u8),
@@ -266,14 +266,23 @@ enum Literal {
Null,
True,
False,
+ NaN,
+ Infinity,
+ NegativeInfinity,
}
impl Literal {
- fn element(&self) -> TapeElement {
+ fn element(&self, bytes: &mut Vec<u8>, offsets: &mut Vec<usize>) ->
TapeElement {
match self {
Literal::Null => TapeElement::Null,
Literal::True => TapeElement::True,
Literal::False => TapeElement::False,
+ Literal::NaN | Literal::Infinity | Literal::NegativeInfinity => {
+ let index = offsets.len() - 1;
+ bytes.extend_from_slice(self.bytes());
+ offsets.push(bytes.len());
+ TapeElement::Number(index as _)
+ }
}
}
@@ -282,6 +291,9 @@ impl Literal {
Literal::Null => "null",
Literal::True => "true",
Literal::False => "false",
+ Literal::NaN => "NaN",
+ Literal::Infinity => "Infinity",
+ Literal::NegativeInfinity => "-Infinity",
}
}
@@ -318,6 +330,9 @@ pub struct TapeDecoder {
/// When `false` (the default), the entire top-level array will be treated
as one row
flatten_top_level_arrays: bool,
+ /// Whether to accept nonstandard NaN and Infinity number literals
+ allow_non_finite_floats: bool,
+
/// A buffer of parsed string data
///
/// Note: if part way through a record, i.e. `stack` is not empty,
@@ -340,6 +355,8 @@ pub struct TapeDecoderOptions {
pub num_fields: usize,
/// Whether to flatten top-level arrays
pub flatten_top_level_arrays: bool,
+ /// Whether to accept nonstandard NaN and Infinity number literals
+ pub allow_non_finite_floats: bool,
}
impl TapeDecoder {
@@ -349,6 +366,7 @@ impl TapeDecoder {
batch_size,
num_fields,
flatten_top_level_arrays,
+ allow_non_finite_floats,
} = options;
let tokens_per_row = 2 + num_fields * 2;
@@ -363,6 +381,7 @@ impl TapeDecoder {
elements,
batch_size,
flatten_top_level_arrays,
+ allow_non_finite_floats,
cur_row: 0,
bytes: Vec::with_capacity(num_fields * 2 * 8),
stack: Vec::with_capacity(10),
@@ -481,6 +500,12 @@ impl TapeDecoder {
self.bytes.push(b);
DecoderState::Number
}
+ b'N' if self.allow_non_finite_floats => {
+ DecoderState::Literal(Literal::NaN, 1)
+ }
+ b'I' if self.allow_non_finite_floats => {
+ DecoderState::Literal(Literal::Infinity, 1)
+ }
b'n' => DecoderState::Literal(Literal::Null, 1),
b'f' => DecoderState::Literal(Literal::False, 1),
b't' => DecoderState::Literal(Literal::True, 1),
@@ -497,7 +522,17 @@ impl TapeDecoder {
b => return Err(err(b, "parsing value")),
};
}
- DecoderState::Number => {
+ state @ DecoderState::Number => {
+ // A leading minus may have arrived in the previous input
buffer.
+ if self.allow_non_finite_floats
+ && iter.peek() == Some(b'I')
+ && self.bytes.last() == Some(&b'-')
+ && self.bytes.len() == self.offsets[self.offsets.len()
- 1] + 1
+ {
+ self.bytes.pop();
+ *state =
DecoderState::Literal(Literal::NegativeInfinity, 1);
+ continue;
+ }
let s = iter.advance_until(|b| {
!matches!(b, b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' |
b'E')
});
@@ -527,7 +562,7 @@ impl TapeDecoder {
}
}
if *idx == bytes.len() as u8 {
- let element = literal.element();
+ let element = literal.element(&mut self.bytes, &mut
self.offsets);
self.stack.pop();
self.elements.push(element);
}
@@ -818,6 +853,7 @@ mod tests {
batch_size: 16,
num_fields: 2,
flatten_top_level_arrays: false,
+ allow_non_finite_floats: false,
})
}
@@ -1130,6 +1166,7 @@ mod tests {
batch_size,
num_fields: 2,
flatten_top_level_arrays: true,
+ allow_non_finite_floats: false,
});
decoder.decode(input.as_bytes()).unwrap();
assert!(!decoder.has_partial_row());