pycontrails.utils.json

JSON utilities.

Functions

dataframe_to_geojson_points(df[, ...])

Convert a pandas DataFrame to a GeoJSON-like dictionary.

Classes

NumpyEncoder(*[, skipkeys, ensure_ascii, ...])

Custom JSONEncoder for numpy data types.

class pycontrails.utils.json.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: JSONEncoder

Custom JSONEncoder for numpy data types.

Examples

>>> import json
>>> import numpy as np
>>> from pycontrails.utils.json import NumpyEncoder
>>> data = np.array([0, 1, 2, 3])
>>> json.dumps(data, cls=NumpyEncoder)
'[0, 1, 2, 3]'
>>> data = np.datetime64(1234567890, "s")
>>> json.dumps(data, cls=NumpyEncoder)
'"2009-02-13T23:31:30"'

Notes

Adapted https://github.com/hmallen/numpyencoder/blob/master/numpyencoder/numpyencoder.py

default(obj)

Encode numpy data types.

This method overrides default() on the JSONEncoder class.

Parameters:

obj (Any) – Object to encode.

Returns:

Any – Encoded object.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
item_separator = ', '
iterencode(o, _one_shot=False)

Encode the given object and yield each string representation as available.

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
key_separator = ': '
pycontrails.utils.json.dataframe_to_geojson_points(df, properties=None, filter_nan=False)

Convert a pandas DataFrame to a GeoJSON-like dictionary.

This function create a Python representation of a GeoJSON FeatureCollection with Point features based on a pandas.DataFrame with geospatial coordinate columns.

Parameters:
  • df (pandas.DataFrame) – Base dataframe. Must contain geospatial coordinate columns [“longitude”, “latitude”, “altitude”, “time”]

  • properties (list[str], optional) – Specify columns to include feature properties. By default, will use all column data that is not in the coordinate columns.

  • filter_nan (bool | list[str], optional) – Filter out points with nan values in any columns, including coordinate columns. If list of str is input, only filter_nan columns will be used for filtering, allowing null values in the other columns.

Returns:

dict[str, Any] – Description

Raises:

KeyError – Raises if properties or filter_nan input contains a column label that does not exist in df