This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathjson.py
More file actions
549 lines (439 loc) · 18.3 KB
/
json.py
File metadata and controls
549 lines (439 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# Copyright 2024 Google LLC
#
# Licensed 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.
"""
JSON functions defined from
https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions
"""
from __future__ import annotations
from typing import Any, cast, Optional, Sequence, Tuple, Union
import warnings
import bigframes.core.utils as utils
import bigframes.dtypes
import bigframes.exceptions as bfe
import bigframes.operations as ops
import bigframes.series as series
from . import array
@utils.preview(name="The JSON-related API `json_set`")
def json_set(
input: series.Series,
json_path_value_pairs: Sequence[Tuple[str, Any]],
) -> series.Series:
"""Produces a new JSON value within a Series by inserting or replacing values at
specified paths.
.. warning::
The JSON-related API `parse_json` is in preview. Its behavior may change in
future versions.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.read_gbq("SELECT JSON '{\\\"a\\\": 1}' AS data")["data"]
>>> bbq.json_set(s, json_path_value_pairs=[("$.a", 100), ("$.b", "hi")])
0 {"a":100,"b":"hi"}
Name: data, dtype: extension<dbjson<JSONArrowType>>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path_value_pairs (Sequence[Tuple[str, Any]]):
Pairs of JSON path and the new value to insert/replace.
Returns:
bigframes.series.Series: A new Series with the transformed JSON data.
"""
# SQLGlot parser does not support the "create_if_missing => true" syntax, so
# create_if_missing is not currently implemented.
result = input
for json_path_value_pair in json_path_value_pairs:
if len(json_path_value_pair) != 2:
raise ValueError(
"Incorrect format: Expected (<json_path>, <json_value>), but found: "
+ f"{json_path_value_pair}"
)
json_path, json_value = json_path_value_pair
result = result._apply_binary_op(
json_value, ops.JSONSet(json_path=json_path), alignment="left"
)
return result
def json_extract(
input: series.Series,
json_path: str,
) -> series.Series:
"""Extracts a JSON value and converts it to a SQL JSON-formatted ``STRING`` or
``JSON`` value. This function uses single quotes and brackets to escape invalid
JSONPath characters in JSON keys.
.. deprecated:: 2.5.0
The ``json_extract`` is deprecated and will be removed in a future version.
Use ``json_query`` instead.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['{"class": {"students": [{"id": 5}, {"id": 12}]}}'])
>>> bbq.json_extract(s, json_path="$.class")
0 {"students":[{"id":5},{"id":12}]}
dtype: string
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
Returns:
bigframes.series.Series: A new Series with the JSON or JSON-formatted STRING.
"""
msg = (
"The `json_extract` is deprecated and will be removed in a future version. "
"Use `json_query` instead."
)
warnings.warn(bfe.format_message(msg), category=UserWarning)
return input._apply_unary_op(ops.JSONExtract(json_path=json_path))
def json_extract_array(
input: series.Series,
json_path: str = "$",
) -> series.Series:
"""Extracts a JSON array and converts it to a SQL array of JSON-formatted
`STRING` or `JSON` values. This function uses single quotes and brackets to
escape invalid JSONPath characters in JSON keys.
.. deprecated:: 2.5.0
The ``json_extract_array`` is deprecated and will be removed in a future version.
Use ``json_query_array`` instead.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['[1, 2, 3]', '[4, 5]'])
>>> bbq.json_extract_array(s)
0 ['1' '2' '3']
1 ['4' '5']
dtype: list<item: string>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": [{"name": "apple"}, {"name": "cherry"}]}',
... '{"fruits": [{"name": "guava"}, {"name": "grapes"}]}'
... ])
>>> bbq.json_extract_array(s, "$.fruits")
0 ['{"name":"apple"}' '{"name":"cherry"}']
1 ['{"name":"guava"}' '{"name":"grapes"}']
dtype: list<item: string>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": {"color": "red", "names": ["apple","cherry"]}}',
... '{"fruits": {"color": "green", "names": ["guava", "grapes"]}}'
... ])
>>> bbq.json_extract_array(s, "$.fruits.names")
0 ['"apple"' '"cherry"']
1 ['"guava"' '"grapes"']
dtype: list<item: string>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
Returns:
bigframes.series.Series: A new Series with the parsed arrays from the input.
"""
msg = (
"The `json_extract_array` is deprecated and will be removed in a future version. "
"Use `json_query_array` instead."
)
warnings.warn(bfe.format_message(msg), category=UserWarning)
return input._apply_unary_op(ops.JSONExtractArray(json_path=json_path))
def json_extract_string_array(
input: series.Series,
json_path: str = "$",
value_dtype: Optional[
Union[bigframes.dtypes.Dtype, bigframes.dtypes.DtypeString]
] = None,
) -> series.Series:
"""Extracts a JSON array and converts it to a SQL array of `STRING` values.
A `value_dtype` can be provided to further coerce the data type of the
values in the array. This function uses single quotes and brackets to escape
invalid JSONPath characters in JSON keys.
.. deprecated:: 2.6.0
The ``json_extract_string_array`` is deprecated and will be removed in a future version.
Use ``json_value_array`` instead.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['[1, 2, 3]', '[4, 5]'])
>>> bbq.json_extract_string_array(s)
0 ['1' '2' '3']
1 ['4' '5']
dtype: list<item: string>[pyarrow]
>>> bbq.json_extract_string_array(s, value_dtype='Int64')
0 [1 2 3]
1 [4 5]
dtype: list<item: int64>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": {"color": "red", "names": ["apple","cherry"]}}',
... '{"fruits": {"color": "green", "names": ["guava", "grapes"]}}'
... ])
>>> bbq.json_extract_string_array(s, "$.fruits.names")
0 ['apple' 'cherry']
1 ['guava' 'grapes']
dtype: list<item: string>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
value_dtype (dtype, Optional):
The data type supported by BigFrames DataFrame.
Returns:
bigframes.series.Series: A new Series with the parsed arrays from the input.
"""
msg = (
"The `json_extract_string_array` is deprecated and will be removed in a future version. "
"Use `json_value_array` instead."
)
warnings.warn(bfe.format_message(msg), category=UserWarning)
array_series = input._apply_unary_op(
ops.JSONExtractStringArray(json_path=json_path)
)
if value_dtype not in [None, bigframes.dtypes.STRING_DTYPE]:
array_items_series = array_series.explode()
if value_dtype == bigframes.dtypes.BOOL_DTYPE:
array_items_series = array_items_series.str.lower() == "true"
else:
array_items_series = array_items_series.astype(value_dtype)
array_series = cast(
series.Series,
array.array_agg(
array_items_series.groupby(level=input.index.names, dropna=False)
),
)
return array_series
def json_query(
input: series.Series,
json_path: str,
) -> series.Series:
"""Extracts a JSON value and converts it to a SQL JSON-formatted ``STRING``
or ``JSON`` value. This function uses double quotes to escape invalid JSONPath
characters in JSON keys. For example: ``"a.b"``.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['{"class": {"students": [{"id": 5}, {"id": 12}]}}'])
>>> bbq.json_query(s, json_path="$.class")
0 {"students":[{"id":5},{"id":12}]}
dtype: string
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
Returns:
bigframes.series.Series: A new Series with the JSON or JSON-formatted STRING.
"""
return input._apply_unary_op(ops.JSONQuery(json_path=json_path))
def json_query_array(
input: series.Series,
json_path: str = "$",
) -> series.Series:
"""Extracts a JSON array and converts it to a SQL array of JSON-formatted
`STRING` or `JSON` values. This function uses double quotes to escape invalid
JSONPath characters in JSON keys. For example: `"a.b"`.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['[1, 2, 3]', '[4, 5]'])
>>> bbq.json_query_array(s)
0 ['1' '2' '3']
1 ['4' '5']
dtype: list<item: string>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": [{"name": "apple"}, {"name": "cherry"}]}',
... '{"fruits": [{"name": "guava"}, {"name": "grapes"}]}'
... ])
>>> bbq.json_query_array(s, "$.fruits")
0 ['{"name":"apple"}' '{"name":"cherry"}']
1 ['{"name":"guava"}' '{"name":"grapes"}']
dtype: list<item: string>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": {"color": "red", "names": ["apple","cherry"]}}',
... '{"fruits": {"color": "green", "names": ["guava", "grapes"]}}'
... ])
>>> bbq.json_query_array(s, "$.fruits.names")
0 ['"apple"' '"cherry"']
1 ['"guava"' '"grapes"']
dtype: list<item: string>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
Returns:
bigframes.series.Series: A new Series with the parsed arrays from the input.
"""
return input._apply_unary_op(ops.JSONQueryArray(json_path=json_path))
def json_value(
input: series.Series,
json_path: str = "$",
) -> series.Series:
"""Extracts a JSON scalar value and converts it to a SQL ``STRING`` value. In
addtion, this function:
- Removes the outermost quotes and unescapes the values.
- Returns a SQL ``NULL`` if a non-scalar value is selected.
- Uses double quotes to escape invalid ``JSON_PATH`` characters in JSON keys.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['{"name": "Jakob", "age": "6"}', '{"name": "Jakob", "age": []}'])
>>> bbq.json_value(s, json_path="$.age")
0 6
1 <NA>
dtype: string
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
Returns:
bigframes.series.Series: A new Series with the JSON-formatted STRING.
"""
return input._apply_unary_op(ops.JSONValue(json_path=json_path))
def json_value_array(
input: series.Series,
json_path: str = "$",
) -> series.Series:
"""
Extracts a JSON array of scalar values and converts it to a SQL ``ARRAY<STRING>``
value. In addition, this function:
- Removes the outermost quotes and unescapes the values.
- Returns a SQL ``NULL`` if the selected value isn't an array or not an array
containing only scalar values.
- Uses double quotes to escape invalid ``JSON_PATH`` characters in JSON keys.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['[1, 2, 3]', '[4, 5]'])
>>> bbq.json_value_array(s)
0 ['1' '2' '3']
1 ['4' '5']
dtype: list<item: string>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": ["apples", "oranges", "grapes"]',
... '{"fruits": ["guava", "grapes"]}'
... ])
>>> bbq.json_value_array(s, "$.fruits")
0 ['apples' 'oranges' 'grapes']
1 ['guava' 'grapes']
dtype: list<item: string>[pyarrow]
>>> s = bpd.Series([
... '{"fruits": {"color": "red", "names": ["apple","cherry"]}}',
... '{"fruits": {"color": "green", "names": ["guava", "grapes"]}}'
... ])
>>> bbq.json_value_array(s, "$.fruits.names")
0 ['apple' 'cherry']
1 ['guava' 'grapes']
dtype: list<item: string>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON data (as native JSON objects or JSON-formatted strings).
json_path (str):
The JSON path identifying the data that you want to obtain from the input.
Returns:
bigframes.series.Series: A new Series with the parsed arrays from the input.
"""
return input._apply_unary_op(ops.JSONValueArray(json_path=json_path))
def json_keys(
input: series.Series,
max_depth: Optional[int] = None,
) -> series.Series:
"""Returns all keys in the root of a JSON object as an ARRAY of STRINGs.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['{"b": {"c": 2}, "a": 1}'], dtype="json")
>>> bbq.json_keys(s)
0 ['a' 'b' 'b.c']
dtype: list<item: string>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON data.
max_depth (int, optional):
Specifies the maximum depth of nested fields to search for keys. If not
provided, searched keys at all levels.
Returns:
bigframes.series.Series: A new Series containing arrays of keys from the input JSON.
"""
return input._apply_unary_op(ops.JSONKeys(max_depth=max_depth))
def to_json(
input: series.Series,
) -> series.Series:
"""Converts a series with a JSON value to a JSON-formatted STRING value.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series([1, 2, 3])
>>> bbq.to_json(s)
0 1
1 2
2 3
dtype: extension<dbjson<JSONArrowType>>[pyarrow]
>>> s = bpd.Series([{"int": 1, "str": "pandas"}, {"int": 2, "str": "numpy"}])
>>> bbq.to_json(s)
0 {"int":1,"str":"pandas"}
1 {"int":2,"str":"numpy"}
dtype: extension<dbjson<JSONArrowType>>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON or JSON-formatted string values.
Returns:
bigframes.series.Series: A new Series with the JSON value.
"""
return input._apply_unary_op(ops.ToJSON())
def to_json_string(
input: series.Series,
) -> series.Series:
"""Converts a series to a JSON-formatted STRING value.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series([1, 2, 3])
>>> bbq.to_json_string(s)
0 1
1 2
2 3
dtype: string
>>> s = bpd.Series([{"int": 1, "str": "pandas"}, {"int": 2, "str": "numpy"}])
>>> bbq.to_json_string(s)
0 {"int":1,"str":"pandas"}
1 {"int":2,"str":"numpy"}
dtype: string
Args:
input (bigframes.series.Series):
The Series to be converted.
Returns:
bigframes.series.Series: A new Series with the JSON-formatted STRING value.
"""
return input._apply_unary_op(ops.ToJSONString())
@utils.preview(name="The JSON-related API `parse_json`")
def parse_json(
input: series.Series,
) -> series.Series:
"""Converts a series with a JSON-formatted STRING value to a JSON value.
.. warning::
The JSON-related API `parse_json` is in preview. Its behavior may change in
future versions.
**Examples:**
>>> import bigframes.pandas as bpd
>>> import bigframes.bigquery as bbq
>>> s = bpd.Series(['{"class": {"students": [{"id": 5}, {"id": 12}]}}'])
>>> s
0 {"class": {"students": [{"id": 5}, {"id": 12}]}}
dtype: string
>>> bbq.parse_json(s)
0 {"class":{"students":[{"id":5},{"id":12}]}}
dtype: extension<dbjson<JSONArrowType>>[pyarrow]
Args:
input (bigframes.series.Series):
The Series containing JSON-formatted strings).
Returns:
bigframes.series.Series: A new Series with the JSON value.
"""
return input._apply_unary_op(ops.ParseJSON())