Path: blob/main/crates/polars-ops/src/chunked_array/strings/json_path.rs
6939 views
use std::borrow::Cow;12use arrow::array::ValueSize;3use jsonpath_lib::PathCompiled;4use polars_core::prelude::arity::{broadcast_try_binary_elementwise, unary_elementwise};5use serde_json::Value;67use super::*;89pub fn extract_json(expr: &PathCompiled, json_str: &str) -> Option<String> {10serde_json::from_str(json_str).ok().and_then(|value| {11// TODO: a lot of heap allocations here. Improve json path by adding a take?12let result = expr.select(&value).ok()?;13let first = *result.first()?;1415match first {16Value::String(s) => Some(s.clone()),17Value::Null => None,18v => Some(v.to_string()),19}20})21}2223/// Returns a string of the most specific value given the compiled JSON path expression.24/// This avoids creating a list to represent individual elements so that they can be25/// selected directly.26pub fn select_json<'a>(expr: &PathCompiled, json_str: &'a str) -> Option<Cow<'a, str>> {27serde_json::from_str(json_str).ok().and_then(|value| {28// TODO: a lot of heap allocations here. Improve json path by adding a take?29let result = expr.select(&value).ok()?;3031let result_str = match result.len() {320 => None,331 => serde_json::to_string(&result[0]).ok(),34_ => serde_json::to_string(&result).ok(),35};3637result_str.map(Cow::Owned)38})39}4041pub trait Utf8JsonPathImpl: AsString {42/// Extract json path, first match43/// Refer to <https://goessner.net/articles/JsonPath/>44fn json_path_match(&self, json_path: &StringChunked) -> PolarsResult<StringChunked> {45let ca = self.as_string();46match (ca.len(), json_path.len()) {47(_, 1) => {48// SAFETY: `json_path` was verified to have exactly 1 element.49let opt_path = unsafe { json_path.get_unchecked(0) };50let out = if let Some(path) = opt_path {51let pat = PathCompiled::compile(path).map_err(52|e| polars_err!(ComputeError: "error compiling JSON path expression {}", e),53)?;54unary_elementwise(ca, |opt_s| opt_s.and_then(|s| extract_json(&pat, s)))55} else {56StringChunked::full_null(ca.name().clone(), ca.len())57};58Ok(out)59},60(len_ca, len_path) if len_ca == 1 || len_ca == len_path => {61broadcast_try_binary_elementwise(ca, json_path, |opt_str, opt_path| {62match (opt_str, opt_path) {63(Some(str_val), Some(path)) => {64PathCompiled::compile(path)65.map_err(|e| polars_err!(ComputeError: "error compiling JSON path expression {}", e))66.map(|path| extract_json(&path, str_val))67},68_ => Ok(None),69}70})71},72(len_ca, len_path) => {73polars_bail!(ComputeError: "The length of `ca` and `json_path` should either 1 or the same, but `{}`, `{}` founded", len_ca, len_path)74},75}76}7778/// Returns the inferred DataType for JSON values for each row79/// in the StringChunked, with an optional number of rows to inspect.80/// When None is passed for the number of rows, all rows are inspected.81fn json_infer(&self, number_of_rows: Option<usize>) -> PolarsResult<DataType> {82let ca = self.as_string();83let values_iter = ca84.iter()85.map(|x| x.unwrap_or("null"))86.take(number_of_rows.unwrap_or(ca.len()));8788polars_json::ndjson::infer_iter(values_iter)89.map(|d| DataType::from_arrow_dtype(&d))90.map_err(|e| polars_err!(ComputeError: "error inferring JSON: {}", e))91}9293/// Extracts a typed-JSON value for each row in the StringChunked94fn json_decode(95&self,96dtype: Option<DataType>,97infer_schema_len: Option<usize>,98) -> PolarsResult<Series> {99let ca = self.as_string();100// Ignore extra fields instead of erroring if the dtype was explicitly given.101let allow_extra_fields_in_struct = dtype.is_some();102let dtype = match dtype {103Some(dt) => dt,104None => ca.json_infer(infer_schema_len)?,105};106let buf_size = ca.get_values_size() + ca.null_count() * "null".len();107let iter = ca.iter().map(|x| x.unwrap_or("null"));108109let array = polars_json::ndjson::deserialize::deserialize_iter(110iter,111dtype.to_arrow(CompatLevel::newest()),112buf_size,113ca.len(),114allow_extra_fields_in_struct,115)116.map_err(|e| polars_err!(ComputeError: "error deserializing JSON: {}", e))?;117Series::try_from((PlSmallStr::EMPTY, array))118}119120fn json_path_select(&self, json_path: &str) -> PolarsResult<StringChunked> {121let pat = PathCompiled::compile(json_path)122.map_err(|e| polars_err!(ComputeError: "error compiling JSONpath expression: {}", e))?;123Ok(self124.as_string()125.apply(|opt_s| opt_s.and_then(|s| select_json(&pat, s))))126}127128fn json_path_extract(129&self,130json_path: &str,131dtype: Option<DataType>,132infer_schema_len: Option<usize>,133) -> PolarsResult<Series> {134let selected_json = self.as_string().json_path_select(json_path)?;135selected_json.json_decode(dtype, infer_schema_len)136}137}138139impl Utf8JsonPathImpl for StringChunked {}140141#[cfg(test)]142mod tests {143use arrow::bitmap::Bitmap;144145use super::*;146147#[test]148fn test_json_select() {149let json_str = r#"{"a":1,"b":{"c":"hello"},"d":[{"e":0},{"e":2},{"e":null}]}"#;150151let compile = |s| PathCompiled::compile(s).unwrap();152let some_cow = |s: &str| Some(Cow::Owned(s.to_string()));153154assert_eq!(select_json(&compile("$"), json_str), some_cow(json_str));155assert_eq!(select_json(&compile("$.a"), json_str), some_cow("1"));156assert_eq!(157select_json(&compile("$.b.c"), json_str),158some_cow(r#""hello""#)159);160assert_eq!(select_json(&compile("$.d[0].e"), json_str), some_cow("0"));161assert_eq!(162select_json(&compile("$.d[2].e"), json_str),163some_cow("null")164);165assert_eq!(166select_json(&compile("$.d[:].e"), json_str),167some_cow("[0,2,null]")168);169}170171#[test]172fn test_json_infer() {173let s = Series::new(174"json".into(),175[176None,177Some(r#"{"a": 1, "b": [{"c": 0}, {"c": 1}]}"#),178Some(r#"{"a": 2, "b": [{"c": 2}, {"c": 5}]}"#),179None,180],181);182let ca = s.str().unwrap();183184let inner_dtype = DataType::Struct(vec![Field::new("c".into(), DataType::Int64)]);185let expected_dtype = DataType::Struct(vec![186Field::new("a".into(), DataType::Int64),187Field::new("b".into(), DataType::List(Box::new(inner_dtype))),188]);189190assert_eq!(ca.json_infer(None).unwrap(), expected_dtype);191// Infereing with the first row will only see None192assert_eq!(ca.json_infer(Some(1)).unwrap(), DataType::Null);193assert_eq!(ca.json_infer(Some(2)).unwrap(), expected_dtype);194}195196#[test]197fn test_json_decode() {198let s = Series::new(199"json".into(),200[201None,202Some(r#"{"a": 1, "b": "hello"}"#),203Some(r#"{"a": 2, "b": "goodbye"}"#),204None,205],206);207let ca = s.str().unwrap();208209let expected_series = StructChunked::from_series(210"".into(),2114,212[213Series::new("a".into(), &[None, Some(1), Some(2), None]),214Series::new("b".into(), &[None, Some("hello"), Some("goodbye"), None]),215]216.iter(),217)218.unwrap()219.with_outer_validity(Some(Bitmap::from_iter([false, true, true, false])))220.into_series();221let expected_dtype = expected_series.dtype().clone();222223assert!(224ca.json_decode(None, None)225.unwrap()226.equals_missing(&expected_series)227);228assert!(229ca.json_decode(Some(expected_dtype), None)230.unwrap()231.equals_missing(&expected_series)232);233}234235#[test]236fn test_json_path_select() {237let s = Series::new(238"json".into(),239[240None,241Some(r#"{"a":1,"b":[{"c":0},{"c":1}]}"#),242Some(r#"{"a":2,"b":[{"c":2},{"c":5}]}"#),243None,244],245);246let ca = s.str().unwrap();247248assert!(249ca.json_path_select("$")250.unwrap()251.into_series()252.equals_missing(&s)253);254255let b_series = Series::new(256"json".into(),257[258None,259Some(r#"[{"c":0},{"c":1}]"#),260Some(r#"[{"c":2},{"c":5}]"#),261None,262],263);264assert!(265ca.json_path_select("$.b")266.unwrap()267.into_series()268.equals_missing(&b_series)269);270271let c_series = Series::new(272"json".into(),273[None, Some(r#"[0,1]"#), Some(r#"[2,5]"#), None],274);275assert!(276ca.json_path_select("$.b[:].c")277.unwrap()278.into_series()279.equals_missing(&c_series)280);281}282283#[test]284fn test_json_path_extract() {285let s = Series::new(286"json".into(),287[288None,289Some(r#"{"a":1,"b":[{"c":0},{"c":1}]}"#),290Some(r#"{"a":2,"b":[{"c":2},{"c":5}]}"#),291None,292],293);294let ca = s.str().unwrap();295296let c_series = Series::new(297"".into(),298[299None,300Some(Series::new("".into(), &[0, 1])),301Some(Series::new("".into(), &[2, 5])),302None,303],304);305306assert!(307ca.json_path_extract("$.b[:].c", None, None)308.unwrap()309.into_series()310.equals_missing(&c_series)311);312}313}314315316