Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862#issuecomment-3050195219 Thank you again @scovich @friendlymatthew and @harshmotw-db for the reviews -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb merged PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862#issuecomment-3050194168 Let's go with this one and then refactor as needed -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
scovich commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2192882471
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
Review Comment:
Hmm. I didn't notice before, but the to-string logic relies on
[serde_json::to_string](https://docs.rs/serde_json/latest/serde_json/fn.to_string.html)
for proper JSON string escaping. So the code really is tied to `serde_json`
crate.
Further, `serde_json::to_string` is fallible, which would not play well with
[std::fmt::Error](https://doc.rust-lang.org/std/fmt/struct.Error.html) used by
`impl Display`:
> This type does not support transmission of an error other than that an
error occurred. This is because, despite the existence of this error, string
formatting is considered an infallible operation. `fmt()` implementors should
not return this `Error` unless they received it from their
[Formatter](https://doc.rust-lang.org/std/fmt/struct.Formatter.html). The only
time your code should create a new instance of this error is when implementing
`fmt::Write`, in order to cancel the formatting operation when writing to the
underlying stream fails.
Probably better to take this as a follow-up item...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
scovich commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2192882471
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
Review Comment:
Hmm. I didn't notice before, but the to-string logic relies on
[serde_json::to_string](https://docs.rs/serde_json/latest/serde_json/fn.to_string.html)
for proper JSON string escaping. So the code really is tied to `serde_json`
crate.
Further, `serde_json::to_string` is fallible, which would not play well with
[std::fmt::Error](https://doc.rust-lang.org/std/fmt/struct.Error.html) used by
`impl Display`:
> This type does not support transmission of an error other than that an
error occurred. This is because, despite the existence of this error, string
formatting is considered an infallible operation. `fmt()` implementors should
not return this `Error` unless they received it from their
[Formatter](https://doc.rust-lang.org/std/fmt/struct.Formatter.html). The only
time your code should create a new instance of this error is when implementing
`fmt::Write`, in order to cancel the formatting operation when writing to the
underlying stream fails.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
scovich commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2192780997
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
+/// let buffer_result = String::from_utf8(buffer)?;
+/// assert_eq!(json_result,
"{\"additional_info\":null,\"age\":30,".to_string() +
+///
"\"email\":\"[email protected]\",\"is_active\":true,\"name\":\"Alice\",\"score\":95.7}");
+/// assert_eq!(json_result, buffer_result);
+/// assert_eq!(json_result, serde_json::to_string(&json_value)?);
+/// # Ok::<(), Box>(())
+/// ```
+pub fn json_to_variant(json: &str, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+let json: Value = serde_json::from_str(json)
+.map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format
error: {e}")))?;
+
+build_json(&json, builder)?;
+Ok(())
+}
+
+fn build_json(json: &Value, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+append_json(json, builder)?;
+Ok(())
+}
+
+fn variant_from_number<'m, 'v>(n: &Number) -> Result,
ArrowError> {
+if let Some(i) = n.as_i64() {
+// Find minimum Integer width to fit
+if i as i8 as i64 == i {
+Ok((i as i8).into())
+} else if i as i16 as i64 == i {
+Ok((i as i16).into())
+} else if i as i32 as i64 == i {
+Ok((i as i32).into())
+} else {
+Ok(i.into())
+}
+} else {
+// Todo: Try decimal once we implement custom JSON parsing where we
have access to strings
+// Try double - currently json_to_variant does not produce decimal
+match n.as_f64() {
+Some(f) => return Ok(f.into()),
+None => Err(ArrowError::InvalidArgumentError(format!(
+"Failed to parse {n} as number",
+))),
+}?
+}
+}
+
+fn append_json<'m, 'v>(
+json: &'v Value,
+builder: &mut impl VariantBuilderExt<'m, 'v>,
+) -> Result<(), ArrowError> {
+match json {
+Value::Null => builder.append_value(Variant::Null),
+Value::Bool(b) => builder.append_value(*b),
+Value::Number(n) => {
+builder.append_value(variant_from_number(n)?);
+}
+Value::String(s) => builder.append_value(s.as_str()),
+Value::Array(arr) => {
+let mut list_builder = builder.new_list();
+for val in arr {
+append_json(val, &mut list_builder)?;
+}
+list_builder.finish();
+}
+Value::Object(obj) => {
+let mut obj_builder = builder.new_object();
+for (key, value) in obj.iter() {
+
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2192413130
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
Review Comment:
> What if we drop variant_to_json_string from the public API, and just impl
Display for Variant instead? Anything fancier would require a json library.
I think this sounds like a good idea to me.
What do you think @harshmotw-db ? I can make the change if we are agreed
(though this PR is getting big as it is)
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = vari
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2192409115
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
+/// let buffer_result = String::from_utf8(buffer)?;
+/// assert_eq!(json_result,
"{\"additional_info\":null,\"age\":30,".to_string() +
+///
"\"email\":\"[email protected]\",\"is_active\":true,\"name\":\"Alice\",\"score\":95.7}");
+/// assert_eq!(json_result, buffer_result);
+/// assert_eq!(json_result, serde_json::to_string(&json_value)?);
+/// # Ok::<(), Box>(())
+/// ```
+pub fn json_to_variant(json: &str, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+let json: Value = serde_json::from_str(json)
+.map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format
error: {e}")))?;
+
+build_json(&json, builder)?;
+Ok(())
+}
+
+fn build_json(json: &Value, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+append_json(json, builder)?;
+Ok(())
+}
+
+fn variant_from_number<'m, 'v>(n: &Number) -> Result,
ArrowError> {
+if let Some(i) = n.as_i64() {
+// Find minimum Integer width to fit
+if i as i8 as i64 == i {
+Ok((i as i8).into())
+} else if i as i16 as i64 == i {
+Ok((i as i16).into())
+} else if i as i32 as i64 == i {
+Ok((i as i32).into())
+} else {
+Ok(i.into())
+}
+} else {
+// Todo: Try decimal once we implement custom JSON parsing where we
have access to strings
+// Try double - currently json_to_variant does not produce decimal
+match n.as_f64() {
+Some(f) => return Ok(f.into()),
+None => Err(ArrowError::InvalidArgumentError(format!(
+"Failed to parse {n} as number",
+))),
+}?
+}
+}
+
+fn append_json<'m, 'v>(
+json: &'v Value,
+builder: &mut impl VariantBuilderExt<'m, 'v>,
+) -> Result<(), ArrowError> {
+match json {
+Value::Null => builder.append_value(Variant::Null),
+Value::Bool(b) => builder.append_value(*b),
+Value::Number(n) => {
+builder.append_value(variant_from_number(n)?);
+}
+Value::String(s) => builder.append_value(s.as_str()),
+Value::Array(arr) => {
+let mut list_builder = builder.new_list();
+for val in arr {
+append_json(val, &mut list_builder)?;
+}
+list_builder.finish();
+}
+Value::Object(obj) => {
+let mut obj_builder = builder.new_object();
+for (key, value) in obj.iter() {
+
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
scovich commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2191131996
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
+/// let buffer_result = String::from_utf8(buffer)?;
+/// assert_eq!(json_result,
"{\"additional_info\":null,\"age\":30,".to_string() +
+///
"\"email\":\"[email protected]\",\"is_active\":true,\"name\":\"Alice\",\"score\":95.7}");
+/// assert_eq!(json_result, buffer_result);
+/// assert_eq!(json_result, serde_json::to_string(&json_value)?);
+/// # Ok::<(), Box>(())
+/// ```
+pub fn json_to_variant(json: &str, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+let json: Value = serde_json::from_str(json)
+.map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format
error: {e}")))?;
+
+build_json(&json, builder)?;
+Ok(())
+}
+
+fn build_json(json: &Value, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+append_json(json, builder)?;
+Ok(())
+}
+
+fn variant_from_number<'m, 'v>(n: &Number) -> Result,
ArrowError> {
+if let Some(i) = n.as_i64() {
+// Find minimum Integer width to fit
+if i as i8 as i64 == i {
+Ok((i as i8).into())
+} else if i as i16 as i64 == i {
+Ok((i as i16).into())
+} else if i as i32 as i64 == i {
+Ok((i as i32).into())
+} else {
+Ok(i.into())
+}
+} else {
+// Todo: Try decimal once we implement custom JSON parsing where we
have access to strings
+// Try double - currently json_to_variant does not produce decimal
+match n.as_f64() {
+Some(f) => return Ok(f.into()),
+None => Err(ArrowError::InvalidArgumentError(format!(
+"Failed to parse {n} as number",
+))),
+}?
+}
+}
+
+fn append_json<'m, 'v>(
+json: &'v Value,
+builder: &mut impl VariantBuilderExt<'m, 'v>,
+) -> Result<(), ArrowError> {
+match json {
+Value::Null => builder.append_value(Variant::Null),
+Value::Bool(b) => builder.append_value(*b),
+Value::Number(n) => {
+builder.append_value(variant_from_number(n)?);
+}
+Value::String(s) => builder.append_value(s.as_str()),
+Value::Array(arr) => {
+let mut list_builder = builder.new_list();
+for val in arr {
+append_json(val, &mut list_builder)?;
+}
+list_builder.finish();
+}
+Value::Object(obj) => {
+let mut obj_builder = builder.new_object();
+for (key, value) in obj.iter() {
+
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
scovich commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2191119514
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
Review Comment:
Every engine needs the ability to convert variant values to strings, in
order to display query results:
```sql
SELECT v FROM t
```
And the string form of a variant column is the output of
`variant_to_json_string`.
This is true regardless of which JSON library they might use (serde_json vs
arrow-json vs. something else entirely), and also true even if they use no JSON
library at all.
In other words,
> we can always put to_json back if a need arises
... will happen the moment an engine actually tries to integrate with
parquet-json and doesn't want to take on a serde-json dependency. The fact that
this PR tries to isolate the serde-json dependency to its own sub-crate is a
claim that such engines exist.
> it is pretty confusing to have json functionality split across two crates
JSON functionality (as in, parsing and manipulating JSON trees) is different
from converting variant values to strings, even if it so happens that the
string form is a JSON value literal?
What if we drop `variant_to_json_string` from the public API, and just `impl
Display for Variant` instead? Anything fancier would require a json library.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2191079133
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
Review Comment:
I agree they are useful in their own right, but I think it is pretty
confusing to have json functionality split across two crates. I suggest we move
all the JSON stuff to a new crate and we can always put to_json back if a need
arises
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2191077755
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
+/// let buffer_result = String::from_utf8(buffer)?;
+/// assert_eq!(json_result,
"{\"additional_info\":null,\"age\":30,".to_string() +
+///
"\"email\":\"[email protected]\",\"is_active\":true,\"name\":\"Alice\",\"score\":95.7}");
+/// assert_eq!(json_result, buffer_result);
+/// assert_eq!(json_result, serde_json::to_string(&json_value)?);
+/// # Ok::<(), Box>(())
+/// ```
+pub fn json_to_variant(json: &str, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+let json: Value = serde_json::from_str(json)
+.map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format
error: {e}")))?;
+
+build_json(&json, builder)?;
+Ok(())
+}
+
+fn build_json(json: &Value, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+append_json(json, builder)?;
+Ok(())
+}
+
+fn variant_from_number<'m, 'v>(n: &Number) -> Result,
ArrowError> {
+if let Some(i) = n.as_i64() {
+// Find minimum Integer width to fit
+if i as i8 as i64 == i {
+Ok((i as i8).into())
+} else if i as i16 as i64 == i {
+Ok((i as i16).into())
+} else if i as i32 as i64 == i {
+Ok((i as i32).into())
+} else {
+Ok(i.into())
+}
+} else {
+// Todo: Try decimal once we implement custom JSON parsing where we
have access to strings
+// Try double - currently json_to_variant does not produce decimal
+match n.as_f64() {
+Some(f) => return Ok(f.into()),
+None => Err(ArrowError::InvalidArgumentError(format!(
+"Failed to parse {n} as number",
+))),
+}?
+}
+}
+
+fn append_json<'m, 'v>(
+json: &'v Value,
+builder: &mut impl VariantBuilderExt<'m, 'v>,
+) -> Result<(), ArrowError> {
+match json {
+Value::Null => builder.append_value(Variant::Null),
+Value::Bool(b) => builder.append_value(*b),
+Value::Number(n) => {
+builder.append_value(variant_from_number(n)?);
+}
+Value::String(s) => builder.append_value(s.as_str()),
+Value::Array(arr) => {
+let mut list_builder = builder.new_list();
+for val in arr {
+append_json(val, &mut list_builder)?;
+}
+list_builder.finish();
+}
+Value::Object(obj) => {
+let mut obj_builder = builder.new_object();
+for (key, value) in obj.iter() {
+
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
harshmotw-db commented on code in PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2191020306 ## parquet-variant-json/src/from_json.rs: ## Review Comment: I presume it's because this PR adds some tests to this file. Moving the tests to a different file should fix it. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
scovich commented on code in PR #7862:
URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2187310530
##
parquet-variant-json/src/from_json.rs:
##
@@ -0,0 +1,690 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Module for parsing JSON strings as Variant
+
+use arrow_schema::ArrowError;
+use parquet_variant::{ListBuilder, ObjectBuilder, Variant, VariantBuilder,
VariantBuilderExt};
+use serde_json::{Number, Value};
+
+/// Converts a JSON string to Variant using [`VariantBuilder`]. The resulting
`value` and `metadata`
+/// buffers can be extracted using `builder.finish()`
+///
+/// # Arguments
+/// * `json` - The JSON string to parse as Variant.
+/// * `variant_builder` - Object of type `VariantBuilder` used to build the
vatiant from the JSON
+/// string
+///
+/// # Returns
+///
+/// * `Ok(())` if successful
+/// * `Err` with error details if the conversion fails
+///
+/// ```rust
+/// # use parquet_variant::VariantBuilder;
+/// # use parquet_variant_json::{
+/// # json_to_variant, variant_to_json_string, variant_to_json,
variant_to_json_value
+/// # };
+///
+/// let mut variant_builder = VariantBuilder::new();
+/// let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string()
+/// + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7,"
+/// + "\"additional_info\": null}";
+/// json_to_variant(&person_string, &mut variant_builder)?;
+///
+/// let (metadata, value) = variant_builder.finish();
+///
+/// let variant = parquet_variant::Variant::try_new(&metadata, &value)?;
+///
+/// let json_result = variant_to_json_string(&variant)?;
+/// let json_value = variant_to_json_value(&variant)?;
+///
+/// let mut buffer = Vec::new();
+/// variant_to_json(&mut buffer, &variant)?;
+/// let buffer_result = String::from_utf8(buffer)?;
+/// assert_eq!(json_result,
"{\"additional_info\":null,\"age\":30,".to_string() +
+///
"\"email\":\"[email protected]\",\"is_active\":true,\"name\":\"Alice\",\"score\":95.7}");
+/// assert_eq!(json_result, buffer_result);
+/// assert_eq!(json_result, serde_json::to_string(&json_value)?);
+/// # Ok::<(), Box>(())
+/// ```
+pub fn json_to_variant(json: &str, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+let json: Value = serde_json::from_str(json)
+.map_err(|e| ArrowError::InvalidArgumentError(format!("JSON format
error: {e}")))?;
+
+build_json(&json, builder)?;
+Ok(())
+}
+
+fn build_json(json: &Value, builder: &mut VariantBuilder) -> Result<(),
ArrowError> {
+append_json(json, builder)?;
+Ok(())
+}
+
+fn variant_from_number<'m, 'v>(n: &Number) -> Result,
ArrowError> {
+if let Some(i) = n.as_i64() {
+// Find minimum Integer width to fit
+if i as i8 as i64 == i {
+Ok((i as i8).into())
+} else if i as i16 as i64 == i {
+Ok((i as i16).into())
+} else if i as i32 as i64 == i {
+Ok((i as i32).into())
+} else {
+Ok(i.into())
+}
+} else {
+// Todo: Try decimal once we implement custom JSON parsing where we
have access to strings
+// Try double - currently json_to_variant does not produce decimal
+match n.as_f64() {
+Some(f) => return Ok(f.into()),
+None => Err(ArrowError::InvalidArgumentError(format!(
+"Failed to parse {n} as number",
+))),
+}?
+}
+}
+
+fn append_json<'m, 'v>(
+json: &'v Value,
+builder: &mut impl VariantBuilderExt<'m, 'v>,
+) -> Result<(), ArrowError> {
+match json {
+Value::Null => builder.append_value(Variant::Null),
+Value::Bool(b) => builder.append_value(*b),
+Value::Number(n) => {
+builder.append_value(variant_from_number(n)?);
+}
+Value::String(s) => builder.append_value(s.as_str()),
+Value::Array(arr) => {
+let mut list_builder = builder.new_list();
+for val in arr {
+append_json(val, &mut list_builder)?;
+}
+list_builder.finish();
+}
+Value::Object(obj) => {
+let mut obj_builder = builder.new_object();
+for (key, value) in obj.iter() {
+
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862#issuecomment-3038812044 @harshmotw-db or @scovich or @friendlymatthew -- could i trouble one of you for a review of this PR? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on code in PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2183595025 ## parquet-variant/examples/variant_from_json_examples.rs: ## @@ -1,50 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one Review Comment: This example duplicated the doc example on `from_json` so I removed it entirely -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
Re: [PR] [Variant] Introduce `parquet-variant-json` crate [arrow-rs]
alamb commented on code in PR #7862: URL: https://github.com/apache/arrow-rs/pull/7862#discussion_r2183594308 ## parquet-variant/tests/test_json_to_variant.rs: ## @@ -1,552 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one Review Comment: I moved these tests into a `mod test` next to the relevant code ## parquet-variant/src/from_json.rs: ## @@ -1,151 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one Review Comment: Moves to new crate -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
