@loaders.gl/json
Version:
Framework-independent loader for JSON and streaming JSON formats
54 lines (53 loc) • 2.21 kB
JavaScript
// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// Copyright 2022 Foursquare Labs, Inc.
import { getTableRowAsObject } from '@loaders.gl/schema';
import { getRowPropertyObject } from "./encode-utils.js";
// Helpers
/**
* Encode a row. Currently this ignores properties in the geometry column.
*/
export function encodeTableRow(table, rowIndex, geometryColumnIndex, utf8Encoder) {
const row = getTableRowAsObject(table, rowIndex);
if (!row)
return;
const featureWithProperties = getFeatureFromRow(table, row, geometryColumnIndex);
const featureString = JSON.stringify(featureWithProperties);
utf8Encoder.push(featureString);
}
/**
* Encode a row as a Feature. Currently this ignores properties objects in the geometry column.
*/
function getFeatureFromRow(table, row, geometryColumnIndex) {
// Extract non-feature/geometry properties
const properties = getRowPropertyObject(table, row, [geometryColumnIndex]);
// Extract geometry feature
const columnName = table.schema?.fields[geometryColumnIndex].name;
let featureOrGeometry = columnName && row[columnName];
// GeoJSON support null geometries
if (!featureOrGeometry) {
// @ts-ignore Feature type does not support null geometries
return { type: 'Feature', geometry: null, properties };
}
// Support string geometries?
// TODO: This assumes GeoJSON strings, which may not be the correct format
// (could be WKT, encoded WKB...)
if (typeof featureOrGeometry === 'string') {
try {
featureOrGeometry = JSON.parse(featureOrGeometry);
}
catch (err) {
throw new Error('Invalid string geometry');
}
}
if (typeof featureOrGeometry !== 'object' || typeof featureOrGeometry?.type !== 'string') {
throw new Error('invalid geometry column value');
}
if (featureOrGeometry?.type === 'Feature') {
// @ts-ignore Feature type does not support null geometries
return { ...featureOrGeometry, properties };
}
// @ts-ignore Feature type does not support null geometries
return { type: 'Feature', geometry: featureOrGeometry, properties };
}