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