polars_genson¶
A Polars plugin for JSON schema inference from string columns using genson-rs.
GensonNamespace ¶
Namespace for JSON schema inference operations.
Source code in polars-genson-py/python/polars_genson/__init__.py
schema_to_json ¶
Convert the DataFrame's schema to JSON string representation.
Returns:
| Type | Description |
|---|---|
str
|
JSON string representation of the DataFrame's schema |
Source code in polars-genson-py/python/polars_genson/__init__.py
infer_polars_schema ¶
infer_polars_schema(
column: str,
*,
ignore_outer_array: bool = True,
ndjson: bool = False,
merge_schemas: bool = True,
debug: bool = False,
profile: bool = False,
verbosity: Literal["Normal", "Verbose"] = "Normal",
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
coerce_strings: bool = False,
avro: bool = True,
map_encoding: Literal["entries", "mapping", "kv"] = "mapping",
wrap_root: bool | str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
) -> pl.Schema
Infer Polars schema from a string column containing JSON data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
Name of the column containing JSON strings |
required |
ignore_outer_array
|
bool
|
Whether to treat top-level arrays as streams of objects |
True
|
ndjson
|
bool
|
Whether to treat input as newline-delimited JSON |
False
|
merge_schemas
|
bool
|
Whether to merge schemas from all rows (True) or return individual schemas (False) |
True
|
debug
|
bool
|
Whether to print debug information |
False
|
profile
|
bool
|
Whether to print profiling information |
False
|
verbosity
|
str
|
Whether to print verbose debug information |
"Normal"
|
map_threshold
|
int
|
Number of keys above which a heterogeneous object may be rewritten as a map (unless overridden). |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Explicit overrides for specific fields. Values must be |
None
|
force_parent_field_types
|
dict[str, str]
|
Explicit overrides for fields based on their parent field name. Values must be |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear
in contexts where other rows provide objects, or scalars of another kind
(an integer and a string, not an integer and a number). This keeps every
value with its type, where the union would keep one kind. The promoted field name defaults
to the parent key with a |
True
|
coerce_strings
|
bool
|
Infer the dtypes for rows that |
False
|
avro
|
bool
|
Whether to infer and convert through an Avro schema (the default) or through
JSON Schema. The Avro route reports the dtypes that |
True
|
map_encoding
|
('mapping', 'entries', 'kv')
|
The |
"mapping"
|
wrap_root
|
str | bool | None
|
If a string, wrap each JSON row under that key before inference.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
Schema | list[Schema]
|
The inferred schema (if merge_schemas=True) or list of schemas (if merge_schemas=False) |
Source code in polars-genson-py/python/polars_genson/__init__.py
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 | |
infer_json_schema ¶
infer_json_schema(
column: str,
*,
ignore_outer_array: bool = True,
ndjson: bool = False,
schema_uri: str | None = "http://json-schema.org/schema#",
merge_schemas: bool = True,
debug: bool = False,
profile: bool = False,
verbosity: Literal["Normal", "Verbose"] = "Normal",
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
avro: bool = False,
wrap_root: bool | str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
) -> dict[str, Any] | list[dict[str, Any]]
Infer JSON schema from a string column containing JSON data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
Name of the column containing JSON strings |
required |
ignore_outer_array
|
bool
|
Whether to treat top-level arrays as streams of objects |
True
|
ndjson
|
bool
|
Whether to treat input as newline-delimited JSON |
False
|
schema_uri
|
str or None
|
Schema URI to use for the generated schema |
"http://json-schema.org/schema#"
|
merge_schemas
|
bool
|
Whether to merge schemas from all rows (True) or return individual schemas (False) |
True
|
debug
|
bool
|
Whether to print debug information |
False
|
profile
|
bool
|
Whether to print profiling information |
False
|
verbosity
|
str
|
Whether to print verbose debug information |
"Normal"
|
map_threshold
|
int
|
Number of keys above which a heterogeneous object may be rewritten as a map (unless overridden). |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Explicit overrides for specific fields. Values must be |
None
|
force_parent_field_types
|
dict[str, str]
|
Explicit overrides for fields based on their parent field name. Values must be |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear
in contexts where other rows provide objects, or scalars of another kind
(an integer and a string, not an integer and a number). This keeps every
value with its type, where the union would keep one kind. The promoted field name defaults
to the parent key with a |
True
|
avro
|
bool
|
Whether to output an Avro schema instead of a JSON Schema. |
False
|
wrap_root
|
str | bool | None
|
If a string, wrap each JSON row under that key before inference.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
dict | list[dict]
|
The inferred JSON schema as a dictionary (if merge_schemas=True) or list of schemas (if merge_schemas=False) |
Source code in polars-genson-py/python/polars_genson/__init__.py
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 | |
normalise_json ¶
normalise_json(
column: str,
*,
decode: bool | Schema = True,
unnest: bool = True,
ignore_outer_array: bool = True,
ndjson: bool = False,
empty_as_null: bool = True,
coerce_strings: bool = False,
map_encoding: Literal["entries", "mapping", "kv"] | None = None,
profile: bool = False,
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
wrap_root: bool | str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
avro_schema: str | dict | None = None,
) -> pl.Series
Normalise a JSON string column to conform to an inferred Avro schema.
This is a higher-level wrapper around :func:normalise_json, returning the
results as a Polars Series instead of an expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
Name of the column containing JSON strings. |
required |
decode
|
bool | Schema
|
Controls how the normalised JSON strings are decoded after normalisation:
|
True
|
unnest
|
bool
|
Whether to expand the decoded struct into a column per field, in place
of a single column of structs. Only applies if |
True
|
ignore_outer_array
|
bool
|
Whether to treat a top-level JSON array as a stream of objects instead of a single array value. |
True
|
ndjson
|
bool
|
Whether the input column contains newline-delimited JSON (NDJSON). |
False
|
empty_as_null
|
bool
|
If True, normalise empty arrays and empty maps to |
True
|
coerce_strings
|
bool
|
If True, attempt to parse numeric/boolean values from strings
(e.g. |
False
|
map_encoding
|
('mapping', 'entries', 'kv')
|
Encoding to use for Avro maps:
- "mapping": plain JSON object ({"en":"Hello"}), decoded as a |
"mapping"
|
profile
|
bool
|
Whether to display timing profile information |
False
|
map_threshold
|
int
|
Threshold above which objects with many varying keys are normalised as Avro maps instead of records. |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference during schema inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Per-field overrides for schema inference (e.g. |
None
|
force_parent_field_types
|
dict[str, str]
|
Per-field overrides for schema inference based on their parent field name (e.g. |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear
in contexts where other rows provide objects, or scalars of another kind
(an integer and a string, not an integer and a number). This keeps every
value with its type, where the union would keep one kind. The promoted field name defaults
to the parent key with a |
True
|
wrap_root
|
str | bool | None
|
If a string, wrap each JSON row under that key before normalisation.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
avro_schema
|
str | dict
|
An Avro schema (as JSON text or a dict) to normalise against in place of
inferring one, for data whose schema is known: the inference pass is
skipped, and the inference options have no effect. Rows are normalised to
it as to an inferred one (fields it lacks dropped, those the rows lack
null, empty arrays and maps null under |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
A Series of normalised JSON data. Each row is rewritten to match the
same Avro schema, with consistent shape across the column.
If |
Source code in polars-genson-py/python/polars_genson/__init__.py
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 | |
schema_to_json ¶
Convert a Polars schema to JSON string representation.
A pl.Map is written as its Arrow storage, a list of {key, value} structs,
as the Rust polars crate has no map dtype, so json_to_schema reads it back as
that list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
Schema
|
The Polars schema to convert to JSON |
required |
debug
|
bool
|
Whether to print debug information |
False
|
Returns:
| Type | Description |
|---|---|
str
|
JSON string representation of the schema |
Source code in polars-genson-py/python/polars_genson/__init__.py
json_to_schema ¶
Convert a JSON string to Polars schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_str
|
str
|
JSON string to convert to Polars schema |
required |
debug
|
bool
|
Whether to print debug information |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
schema |
Schema
|
The Polars schema representation of the JSON |
Source code in polars-genson-py/python/polars_genson/__init__.py
plug ¶
Wrap Polars' register_plugin_function helper to always pass the same lib.
Pass changes_length when using the merge_schemas (per-row) inference, as we only
build a single schema in that case (so it'd be a waste to make more than one row).
Source code in polars-genson-py/python/polars_genson/__init__.py
infer_json_schema ¶
infer_json_schema(
expr: Expr,
*,
ignore_outer_array: bool = True,
ndjson: bool = False,
schema_uri: str | None = "http://json-schema.org/schema#",
merge_schemas: bool = True,
debug: bool = False,
profile: bool = False,
verbosity: Literal["Normal", "Verbose"] = "Normal",
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
avro: bool = False,
wrap_root: str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
) -> pl.Expr
Infer JSON schema from a string column containing JSON data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
Expression representing a string column containing JSON data |
required |
ignore_outer_array
|
bool
|
Whether to treat top-level arrays as streams of objects |
True
|
ndjson
|
bool
|
Whether to treat input as newline-delimited JSON |
False
|
schema_uri
|
str or None
|
Schema URI to use for the generated schema |
"http://json-schema.org/schema#"
|
merge_schemas
|
bool
|
Whether to merge schemas from all rows (True) or return individual schemas (False) |
True
|
debug
|
bool
|
Whether to print debug information |
False
|
profile
|
bool
|
Whether to print profiling information |
False
|
verbosity
|
str
|
Whether to print verbose debug information |
"Normal"
|
map_threshold
|
int
|
Number of keys above which a heterogeneous object may be rewritten as a map (unless overridden). |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count (preserves existing behavior). |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Explicit overrides for specific fields. Values must be |
None
|
force_parent_field_types
|
dict[str, str]
|
Explicit overrides for fields based on their parent field name. Values must be |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear
in contexts where other rows provide objects, or scalars of another kind
(an integer and a string, not an integer and a number). This keeps every
value with its type, where the union would keep one kind. The promoted field name defaults
to the parent key with a |
True
|
avro
|
bool
|
Whether to output an Avro schema instead of a JSON Schema. |
False
|
wrap_root
|
str | None
|
If a string, wrap each JSON row under that key before inference.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
Expr
|
Expression representing the inferred JSON schema |
Source code in polars-genson-py/python/polars_genson/__init__.py
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 | |
infer_polars_schema ¶
infer_polars_schema(
expr: Expr,
*,
ignore_outer_array: bool = True,
ndjson: bool = False,
merge_schemas: bool = True,
debug: bool = False,
profile: bool = False,
verbosity: Literal["Normal", "Verbose"] = "Normal",
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
coerce_strings: bool = False,
avro: bool = True,
wrap_root: str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
) -> pl.Expr
Infer Polars schema from a string column containing JSON data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
Expression representing a string column containing JSON data |
required |
ignore_outer_array
|
bool
|
Whether to treat top-level arrays as streams of objects |
True
|
ndjson
|
bool
|
Whether to treat input as newline-delimited JSON |
False
|
merge_schemas
|
bool
|
Whether to merge schemas from all rows (True) or return individual schemas (False) |
True
|
debug
|
bool
|
Whether to print debug information |
False
|
profile
|
bool
|
Whether to print profiling information |
False
|
verbosity
|
str
|
Whether to print verbose debug information |
"Normal"
|
map_threshold
|
int
|
Number of keys above which a heterogeneous object may be rewritten as a map (unless overridden). |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Explicit overrides for specific fields. Values must be |
None
|
force_parent_field_types
|
dict[str, str]
|
Explicit overrides for fields based on their parent field name. Values must be |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear
in contexts where other rows provide objects, or scalars of another kind
(an integer and a string, not an integer and a number). This keeps every
value with its type, where the union would keep one kind. The promoted field name defaults
to the parent key with a |
True
|
coerce_strings
|
bool
|
Infer the dtypes for rows that |
False
|
avro
|
bool
|
Whether to infer and convert through an Avro schema (the default) or through
JSON Schema. The Avro route reports the dtypes that |
True
|
wrap_root
|
str | None
|
If a string, wrap each JSON row under that key before inference.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
Expr
|
Expression yielding the inferred Polars schema (as a struct of {name, dtype} fields). |
Source code in polars-genson-py/python/polars_genson/__init__.py
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 | |
normalise_json ¶
normalise_json(
expr: Expr,
*,
ignore_outer_array: bool = True,
ndjson: bool = False,
empty_as_null: bool = True,
coerce_strings: bool = False,
map_encoding: Literal["entries", "mapping", "kv"] = "mapping",
profile: bool = False,
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
wrap_root: str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
avro_schema: str | dict | None = None,
) -> pl.Expr
Normalise a JSON string column against an inferred Avro schema.
This performs schema inference once across all rows, then rewrites each row to conform to that schema. The output is a new column of JSON strings with consistent structure and datatypes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr
|
Expression representing a string column of JSON data. |
required |
ignore_outer_array
|
bool
|
Treat a top-level JSON array as a stream of objects (like NDJSON). |
True
|
ndjson
|
bool
|
Treat input as newline-delimited JSON rather than a single JSON document. |
False
|
empty_as_null
|
bool
|
Convert empty arrays/maps into |
True
|
coerce_strings
|
bool
|
If True, attempt to coerce string values into numeric/boolean types where the schema expects them. If False, unmatched strings become null. |
False
|
map_encoding
|
('mapping', 'entries', 'kv')
|
Encoding to use for Avro maps:
- "mapping": plain JSON object ({"en":"Hello"}), decoded as a |
"mapping"
|
profile
|
bool
|
Whether to show timing profile output |
False
|
map_threshold
|
int
|
Maximum number of keys before an object is treated as a map (unless overridden). |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference during schema inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Override the inferred type for specific fields. Keys are field names,
values must be either |
None
|
force_parent_field_types
|
dict[str, str]
|
Override the inferred type for specific fields based on their parent field name.
Keys are field names, values must be either |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear
in contexts where other rows provide objects, or scalars of another kind
(an integer and a string, not an integer and a number). This keeps every
value with its type, where the union would keep one kind. The promoted field name defaults
to the parent key with a |
True
|
wrap_root
|
str | None
|
Wrap each JSON row under that key before normalisation.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
avro_schema
|
str | dict
|
An Avro schema (as JSON text or a dict) to normalise against in place of inferring one, for data whose schema is known: the inference pass is skipped, and the inference options have no effect. |
None
|
Returns:
| Type | Description |
|---|---|
Expr
|
An expression producing a new string column, where each row is a normalised JSON object matching the inferred Avro schema. |
Examples:
>>> df = pl.DataFrame({
... "json_data": [
... '{"id": "1", "labels": {}}',
... '{"id": 2, "labels": {"en": "Hello"}}',
... ]
... })
>>> df.select(normalise_json(pl.col("json_data")))
shape: (2, 1)
┌──────────────────────────────────────┐
│ normalised │
│ --- │
│ str │
╞══════════════════════════════════════╡
│ {"id": "1", "labels": null} │
│ {"id": "2", "labels": {"en":"Hello"}}│
└──────────────────────────────────────┘
Source code in polars-genson-py/python/polars_genson/__init__.py
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 | |
infer_from_parquet ¶
infer_from_parquet(
input_path: str | Path,
column: str,
output_path: str | Path | None = None,
*,
ignore_outer_array: bool = True,
ndjson: bool = False,
schema_uri: str | None = "http://json-schema.org/schema#",
debug: bool = False,
profile: bool = False,
verbosity: Literal["Normal", "Verbose"] = "Normal",
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
avro: bool = False,
wrap_root: str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
) -> str | dict
Infer JSON schema from a Parquet column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str | Path
|
Path to input Parquet file |
required |
column
|
str
|
Name of column containing JSON strings |
required |
output_path
|
str | Path
|
Path to write schema JSON. If None, returns schema as dict |
None
|
ignore_outer_array
|
bool
|
Whether to treat top-level arrays as streams of objects |
True
|
ndjson
|
bool
|
Whether to treat input as newline-delimited JSON |
False
|
schema_uri
|
str or None
|
Schema URI to use for the generated schema |
"http://json-schema.org/schema#"
|
debug
|
bool
|
Whether to print debug information |
False
|
profile
|
bool
|
Whether to print profiling information |
False
|
verbosity
|
str
|
Whether to print verbose debug information |
"Normal"
|
map_threshold
|
int
|
Number of keys above which a heterogeneous object may be rewritten as a map (unless overridden). |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Explicit overrides for specific fields. Values must be |
None
|
force_parent_field_types
|
dict[str, str]
|
Explicit overrides for fields based on their parent field name. Values must be |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear in contexts where other rows provide objects, or scalars of another kind (an integer and a string, not an integer and a number). |
True
|
avro
|
bool
|
Whether to output an Avro schema instead of a JSON Schema. |
False
|
wrap_root
|
str | None
|
If a string, wrap each JSON row under that key before inference.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
str | dict
|
If output_path is given, returns success message. If output_path is None, returns schema as dict. |
Examples:
>>> # Infer schema and return as dict
>>> schema = infer_from_parquet("data.parquet", "claims")
>>> # Infer schema and write to file
>>> infer_from_parquet("data.parquet", "claims", "schema.json")
Source code in polars-genson-py/python/polars_genson/__init__.py
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | |
normalise_from_parquet ¶
normalise_from_parquet(
input_path: str | Path,
column: str,
output_path: str | Path | None,
*,
output_column: str | None = None,
ignore_outer_array: bool = True,
ndjson: bool = False,
empty_as_null: bool = True,
coerce_strings: bool = False,
map_encoding: Literal["entries", "mapping", "kv"] = "mapping",
debug: bool = False,
profile: bool = False,
map_threshold: int = 20,
map_max_required_keys: int | None = None,
unify_maps: bool = False,
no_unify: set[str] | None = None,
force_field_types: dict[str, str] | None = None,
force_parent_field_types: dict[str, str] | None = None,
force_scalar_promotion: set[str] | None = None,
wrap_scalars: bool = True,
wrap_root: str | None = None,
no_root_map: bool = True,
max_builders: int | None = None,
typed: bool = False,
keep_columns: list[str] | None = None,
extract_invariants: dict[str, str] | None = None,
lookup_output_path: str | Path | None = None,
prune: set[str] | None = None,
prune_output_path: str | Path | None = None,
schema: Schema | Struct | None = None,
schema_check: Literal["compatible", "strict", "none"] = "compatible",
unnest: bool = False,
output_format: Literal["parquet", "arrow"] = "parquet",
avro_schema: str | dict | None = None,
) -> Any
Normalise JSON data from a Parquet column and write back to Parquet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str | Path
|
Path to input Parquet file |
required |
column
|
str
|
Name of column containing JSON strings |
required |
output_path
|
str | Path | None
|
Path to write normalised Parquet file (can be same as input_path for in-place).
None with |
required |
output_column
|
str
|
Name for output column. Defaults to same as input column name |
None
|
ignore_outer_array
|
bool
|
Whether to treat a top-level JSON array as a stream of objects instead of a single array value. |
True
|
ndjson
|
bool
|
Whether the input column contains newline-delimited JSON (NDJSON). |
False
|
empty_as_null
|
bool
|
If True, normalise empty arrays and empty maps to |
True
|
coerce_strings
|
bool
|
If True, attempt to parse numeric/boolean values from strings
(e.g. |
False
|
map_encoding
|
('mapping', 'entries', 'kv')
|
Encoding to use for Avro maps:
- "mapping": plain JSON object ({"en":"Hello"}), decoded as a |
"mapping"
|
debug
|
bool
|
Whether to print debug information |
False
|
profile
|
bool
|
Whether to display timing profile information |
False
|
map_threshold
|
int
|
Threshold above which objects with many varying keys are normalised as Avro maps instead of records. |
20
|
map_max_required_keys
|
int
|
Maximum number of required keys allowed for Map inference during schema inference. Objects with more required keys will be forced to Record type. If None, no gating based on required key count. |
None
|
unify_maps
|
bool
|
Enable unification of compatible but non-homogeneous record schemas into maps. When True, record schemas with compatible field types can be merged into a single map schema with selective nullable fields. |
False
|
no_unify
|
set[str] | None
|
Prevent unification of keys under these field names with their sibling record fields. |
None
|
force_field_types
|
dict[str, str]
|
Per-field overrides for schema inference (e.g. |
None
|
force_parent_field_types
|
dict[str, str]
|
Per-field overrides for schema inference based on their parent field name (e.g. |
None
|
force_scalar_promotion
|
set[str]
|
Set of field names that should always be promoted to wrapped scalars,
even when they appear as simple scalars. Ensures schema stability for
fields known to have heterogeneous types across chunks.
Example: |
None
|
wrap_scalars
|
bool
|
Whether to promote scalar values into singleton objects when they appear in contexts where other rows provide objects, or scalars of another kind (an integer and a string, not an integer and a number). |
True
|
wrap_root
|
str | None
|
If a string, wrap each JSON row under that key before normalisation.
If |
None
|
no_root_map
|
bool
|
Prevent document root from becoming a map type, even if it meets map inference criteria |
True
|
max_builders
|
int
|
Maximum number of schema builders to create in parallel at once. Lower values reduce peak memory usage during schema inference. If None, processes all strings at once. Default is None. |
None
|
typed
|
bool
|
If True, write the normalised rows as a typed struct column (the dtype
|
False
|
keep_columns
|
list[str]
|
Input columns (e.g. an |
None
|
extract_invariants
|
dict[str, str]
|
Fields that are invariant per key, each mapped to its determinant: the sibling
field whose value determines it, e.g. |
None
|
lookup_output_path
|
str | Path
|
Parquet file for the lookup table, with string columns |
None
|
prune
|
set[str]
|
Record fields, at any depth, whose records are pruned: wherever a record holds a
non-null value for one, the record is removed, and each removed value is written
to |
None
|
prune_output_path
|
str | Path
|
Parquet file for the pruned values, one row each: the |
None
|
schema
|
Schema | Struct
|
A target schema for the output column (the fields of its struct), for output
that has the same schema whatever the rows held, such as chunks of one dataset
normalised one at a time. The rows are normalised against the inferred schema,
which is checked against the target (see |
None
|
schema_check
|
('compatible', 'strict', 'none')
|
How the inferred schema is checked against |
"compatible"
|
unnest
|
bool
|
Write the output struct's fields as top-level columns (after |
False
|
output_format
|
('parquet', 'arrow')
|
"arrow" writes no output file and returns the output's record batches as an
Arrow C stream (the Arrow PyCapsule interface, |
"parquet"
|
avro_schema
|
str | dict
|
An Avro schema (JSON text or a dict) expected to hold the rows, such as one
inferred before from data of the same shape with the same options. Where every
row fits it strictly (its own inferred schema adds nothing to it: no member it
lacks, no value of a type its node does not hold, no union of two or more types
in it) and it fits |
None
|
Returns:
| Type | Description |
|---|---|
The Arrow C stream with ``output_format="arrow"``, else None.
|
|
Examples:
>>> # Normalize and write to new file
>>> normalise_from_parquet(
... "input.parquet",
... "claims",
... "output.parquet",
... map_threshold=0,
... unify_maps=True
... )
>>> # In-place normalization (overwrites source)
>>> normalise_from_parquet(
... "data.parquet",
... "claims",
... "data.parquet"
... )
Source code in polars-genson-py/python/polars_genson/__init__.py
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 | |
check_schema_compatibility ¶
check_schema_compatibility(
inferred: Schema | Struct,
target: Schema | Struct,
schema_check: Literal["compatible", "strict"] = "compatible",
) -> list[str]
Report where an inferred schema does not fit a target schema.
One line per offending field: its path (a.b[].c, [] for list items, {}
for map values) and why. An empty list means it fits.
Under "compatible", inferred fits target when, recursively, it is Null (no
value was seen), which fits any dtype; it is the same dtype, with no widening (an
Int64 does not fit a Float64); or both are structs, lists, arrays of one size
or maps whose parts fit, a struct having only fields the target has (the target may
have more, written as nulls by normalise_from_parquet(schema=...)). A target
field typed Null takes only Null. Under "strict", inferred must be target,
field for field.
Source code in polars-genson-py/python/polars_genson/__init__.py
read_parquet_metadata ¶
Read metadata from a Parquet file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the Parquet file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dictionary of metadata key-value pairs |
Source code in polars-genson-py/python/polars_genson/__init__.py
write_parquet ¶
write_parquet(
data: Any,
path: str | Path,
*,
row_group_size: int | None = None,
column_encoding: Mapping[str, str] | None = None,
) -> None
Write Arrow data to a Parquet file with genson's Parquet writer.
The writer genson writes its own output with, for any Arrow data: its row groups' leaf columns are encoded in parallel, so a deeply nested table (lists of structs of lists) writes in a fraction of the time of a writer that encodes them one at a time. The data is taken through the Arrow PyCapsule interface, its buffers not copied, and the GIL is released while it is encoded.
The file holds the same data in the same Arrow schema as pyarrow.parquet writes
it: list and map groups take the Parquet specification's names (element,
key_value), as pyarrow names them, and the Arrow schema is stored in the file's
metadata. It is compressed with zstd (level 1). Each leaf column is dictionary
encoded but one whose first values (up to 16,384, at least 128) are more than three
quarters distinct, for which a dictionary costs a hash per value and grows the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Arrow data with an |
required |
path
|
str | Path
|
Path to write the Parquet file to. An existing file is replaced. |
required |
row_group_size
|
int
|
Rows to a row group. Defaults to 1,048,576 (arrow-rs's default, and pyarrow's). |
None
|
column_encoding
|
Mapping[str, str]
|
Leaf columns written in an encoding of their own, with no dictionary: each leaf's
path in the Parquet schema ( |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
OSError
|
If the file cannot be written. |
Source code in polars-genson-py/python/polars_genson/__init__.py
avro_to_polars_schema ¶
avro_to_polars_schema(
avro_schema_json: str,
debug: bool = False,
*,
map_encoding: Literal["entries", "mapping", "kv"] = "mapping",
) -> pl.Schema
Convert an Avro schema to a Polars Schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
avro_schema_json
|
str
|
JSON string containing Avro schema |
required |
debug
|
bool
|
Whether to print debug information |
False
|
map_encoding
|
('mapping', 'entries', 'kv')
|
The |
"mapping"
|
Returns:
| Type | Description |
|---|---|
Schema
|
Polars schema representation |
Source code in polars-genson-py/python/polars_genson/__init__.py
schema_to_dict ¶
Convert a Polars Schema into a nested Python dict.
Source code in polars-genson-py/python/polars_genson/__init__.py
dtypes ¶
Dtype parsing from concise string format used to serialise across Rust to Python.
contains_map ¶
Whether a dtype is, or holds, a pl.Map.
Source code in polars-genson-py/python/polars_genson/dtypes.py
project_dtype ¶
expr, of dtype have, as str.json_decode decodes the same values to want.
want's struct fields are taken by name (a field have lacks is null, one want
lacks is dropped) and lists are projected element by element. None where the
result could differ from json_decode's: a leaf, map or array dtype other than
have's (where a cast and json_decode's parse can disagree), or a nested want
where have holds only nulls. Structs are built field by field, never cast, so
no cast drops a struct field.
Source code in polars-genson-py/python/polars_genson/dtypes.py
typed_route_makes ¶
Whether dtype holds only dtypes the typed route can decode to.
Those are the ones avro_to_polars_schema gives an Avro schema: String, Int64,
Float64, Boolean and Null leaves, in lists, structs and maps keyed by String. A dtype
holding any other (Categorical, Int32, Datetime, Decimal, Array, ...) never projects,
so it is decoded from JSON text without running the typed route first.
Source code in polars-genson-py/python/polars_genson/dtypes.py
dtype_spec ¶
Describe a dtype (or a schema, as a struct of its columns) for a target schema.
The JSON-ready description the Rust side reads (genson_core::conform::
data_type_from_spec): a dtype name such as "String", or {"Struct": [[name,
dtype], ...]}, {"List": dtype}, {"Array": [dtype, size]} or {"Map":
[key, value]}.
Source code in polars-genson-py/python/polars_genson/dtypes.py
polars ¶
Extend polars DataFrame with genson namespace.
utils ¶
Utility functions for polars-genson plugin.
parse_into_expr ¶
parse_into_expr(
expr: IntoExpr,
*,
str_as_lit: bool = False,
list_as_lit: bool = True,
dtype: PolarsDataType | None = None,
) -> pl.Expr
Convert the user input into a polars.Expr.
- If
expris already anpl.Expr, we return it as-is. - If
expris a string andstr_as_lit=False, interpret aspl.col(expr). - Otherwise, treat it as a literal (possibly typed by
dtype).
Source code in polars-genson-py/python/polars_genson/utils.py
parse_version ¶
Split a version string like "0.20.16" into a tuple of ints, e.g. (0, 20, 16).