Skip to content

feature: Add JSON Lines serializer #1760

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 28, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/sagemaker/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,34 @@ def serialize(self, data):
return json.dumps(data)


class JSONLinesSerializer(BaseSerializer):
"""Serialize data to a JSON Lines formatted string."""

CONTENT_TYPE = "application/jsonlines"

def serialize(self, data):
"""Serialize data of various formats to a JSON Lines formatted string.

Args:
data (object): Data to be serialized. The data can be a string,
list of JSON serializable objects, or a file-like object.

Returns:
str: The data serialized as a string containing newline-separated
JSON values.
"""
if isinstance(data, str):
return data

if isinstance(data, list):
return "\n".join(json.dumps(element) for element in data)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code will not serialize the last line correctly, according to the POSIX standard:

https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206


if hasattr(data, "read"):
return data.read()

raise ValueError("Object of type %s is not JSON Lines serializable." % type(data))


class SparseMatrixSerializer(BaseSerializer):
"""Serialize a sparse matrix to a buffer using the .npz format."""

Expand Down
52 changes: 52 additions & 0 deletions tests/unit/sagemaker/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
NumpySerializer,
JSONSerializer,
SparseMatrixSerializer,
JSONLinesSerializer,
)
from tests.unit import DATA_DIR

Expand Down Expand Up @@ -235,6 +236,57 @@ def test_json_serializer_csv_buffer(json_serializer):
assert result == validation_value


@pytest.fixture
def json_lines_serializer():
return JSONLinesSerializer()


@pytest.mark.parametrize(
"input, expected",
[
('["Name", "Score"]\n["Gilbert", 24]', '["Name", "Score"]\n["Gilbert", 24]'),
(
'{"Name": "Gilbert", "Score": 24}\n{"Name": "Alexa", "Score": 29}',
'{"Name": "Gilbert", "Score": 24}\n{"Name": "Alexa", "Score": 29}',
),
],
)
def test_json_lines_serializer_string(json_lines_serializer, input, expected):
actual = json_lines_serializer.serialize(input)
assert actual == expected


@pytest.mark.parametrize(
"input, expected",
[
([["Name", "Score"], ["Gilbert", 24]], '["Name", "Score"]\n["Gilbert", 24]'),
(
[{"Name": "Gilbert", "Score": 24}, {"Name": "Alexa", "Score": 29}],
'{"Name": "Gilbert", "Score": 24}\n{"Name": "Alexa", "Score": 29}',
),
],
)
def test_json_lines_serializer_list(json_lines_serializer, input, expected):
actual = json_lines_serializer.serialize(input)
assert actual == expected


@pytest.mark.parametrize(
"source, expected",
[
('["Name", "Score"]\n["Gilbert", 24]', '["Name", "Score"]\n["Gilbert", 24]'),
(
'{"Name": "Gilbert", "Score": 24}\n{"Name": "Alexa", "Score": 29}',
'{"Name": "Gilbert", "Score": 24}\n{"Name": "Alexa", "Score": 29}',
),
],
)
def test_json_lines_serializer_file_like(json_lines_serializer, source, expected):
input = io.StringIO(source)
actual = json_lines_serializer.serialize(input)
assert actual == expected


@pytest.fixture
def sparse_matrix_serializer():
return SparseMatrixSerializer()
Expand Down