-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[VARIANT] Add support for the json_to_variant API #7783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
43 commits
Select commit
Hold shift + click to select a range
87b438d
add json_to_variant
harshmotw-db a946ac6
comment fix
harshmotw-db bca3b81
Added another sample buffer managger
harshmotw-db 339e880
minor refactoring
harshmotw-db fe798c3
Merge branch 'main' of https://github.com/harshmotw-db/arrow-rs into …
harshmotw-db 882d3a7
Merge branch 'main' of https://github.com/harshmotw-db/arrow-rs into …
harshmotw-db 3c18fdf
incorporated new changes
harshmotw-db 67a83fe
minor changes
harshmotw-db c9aa519
Merge branch 'main' of https://github.com/harshmotw-db/arrow-rs into …
harshmotw-db dede88d
test fix based on recent commit
harshmotw-db fa3befc
constant fix
harshmotw-db 38bac59
fix
harshmotw-db cd530ee
addressed comments
harshmotw-db 57b3eb0
fix
harshmotw-db 71b7d6f
fixed VariantBufferManager
harshmotw-db 031c916
deduped a bit of code
harshmotw-db d4fc876
deduplicated code
harshmotw-db c41af4e
moved serde code out of variant.rs
harshmotw-db ecaf557
incorporated Ryan's latest comments
harshmotw-db 4abc598
add more object tests
harshmotw-db 0842ef8
fix
harshmotw-db 94531af
doc fix
harshmotw-db 28d0012
Merge branch 'main' into harsh-motwani_data/from_json
harshmotw-db e2788f5
Removed dependency on VariantBufferManager and leave that to later
harshmotw-db 3178449
Merge branch 'harsh-motwani_data/from_json' of https://github.com/har…
harshmotw-db 0455685
fix
harshmotw-db cc0b66e
fix
harshmotw-db d2a7516
resolved test comment
harshmotw-db a29b5c3
fixed more comments
harshmotw-db 7f23cf5
fix decimal to string
harshmotw-db 50f4b25
fmt and clippy
harshmotw-db 560e430
fix
harshmotw-db 3249d93
Merge remote-tracking branch 'apache/main' into harsh-motwani_data/fr…
alamb 07d5688
clippy
alamb af937ac
Split tests into separate functions
alamb 388f188
partially removed decimal dependency
harshmotw-db 7407776
merge
harshmotw-db 3b42d91
removed decimal type from variant json parsing
harshmotw-db 43d6ea5
comment fix
harshmotw-db e9deda9
refined lifetimes
harshmotw-db eb11890
Fix clippy, remove unused dependency
alamb 3531540
Merge remote-tracking branch 'apache/main' into harsh-motwani_data/fr…
alamb ea5b573
Update parquet-variant/src/from_json.rs
alamb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| // 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. | ||
|
|
||
| //! Example showing how to convert Variant values to JSON | ||
|
|
||
| use parquet_variant::{ | ||
| json_to_variant, variant_to_json, variant_to_json_string, variant_to_json_value, VariantBuilder, | ||
| }; | ||
|
|
||
| fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
| let person_string = "{\"name\":\"Alice\", \"age\":30, ".to_string() | ||
| + "\"email\":\"[email protected]\", \"is_active\": true, \"score\": 95.7," | ||
| + "\"additional_info\": null}"; | ||
|
|
||
| let mut variant_builder = VariantBuilder::new(); | ||
| 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 pretty_json = serde_json::to_string_pretty(&json_value)?; | ||
| println!("{pretty_json}"); | ||
|
|
||
| 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(()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
alamb marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| // 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 crate::{ListBuilder, ObjectBuilder, Variant, VariantBuilder, VariantBuilderExt}; | ||
| use arrow_schema::ArrowError; | ||
| 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::{ | ||
| /// json_to_variant, variant_to_json, variant_to_json_string, variant_to_json_value, VariantBuilder | ||
| /// }; | ||
| /// | ||
| /// 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<dyn std::error::Error>>(()) | ||
| /// ``` | ||
| 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<Variant<'m, 'v>, 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() { | ||
| let mut field_builder = ObjectFieldBuilder { | ||
| key, | ||
| builder: &mut obj_builder, | ||
| }; | ||
| append_json(value, &mut field_builder)?; | ||
| } | ||
| obj_builder.finish()?; | ||
| } | ||
| }; | ||
| Ok(()) | ||
| } | ||
|
|
||
| struct ObjectFieldBuilder<'s, 'o, 'v> { | ||
| key: &'s str, | ||
| builder: &'o mut ObjectBuilder<'v, 's>, | ||
| } | ||
|
|
||
| impl<'m, 'v> VariantBuilderExt<'m, 'v> for ObjectFieldBuilder<'_, '_, '_> { | ||
| fn append_value(&mut self, value: impl Into<Variant<'m, 'v>>) { | ||
| self.builder.insert(self.key, value); | ||
| } | ||
|
|
||
| fn new_list(&mut self) -> ListBuilder { | ||
| self.builder.new_list(self.key) | ||
| } | ||
|
|
||
| fn new_object(&mut self) -> ObjectBuilder { | ||
| self.builder.new_object(self.key) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,10 +33,12 @@ mod decoder; | |
| mod variant; | ||
| // TODO: dead code removal | ||
| mod builder; | ||
| mod from_json; | ||
| mod to_json; | ||
| #[allow(dead_code)] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This allow was bothering me , so here is a PR to clean it up: |
||
| mod utils; | ||
|
|
||
| pub use builder::*; | ||
| pub use from_json::json_to_variant; | ||
| pub use to_json::{variant_to_json, variant_to_json_string, variant_to_json_value}; | ||
| pub use variant::*; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.