Skip to content

Commit

Permalink
Add JSON to CSV parser
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers committed Mar 23, 2024
1 parent aa85549 commit 4249dc0
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 5 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
CHANGELOG
=========

0.5.2
-----

- Add json_to_csv converter


0.5.1
-----

Expand Down
4 changes: 2 additions & 2 deletions py_partiql_parser/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
__version__ = "0.5.1"
__version__ = "0.5.2"


from ._internal.parser import DynamoDBStatementParser, S3SelectParser # noqa
from ._internal.json_parser import SelectEncoder # noqa
from ._internal.csv_converter import csv_to_json # noqa
from ._internal.csv_converter import csv_to_json, json_to_csv # noqa
from ._internal.utils import MissingVariable, QueryMetadata # noqa
11 changes: 10 additions & 1 deletion py_partiql_parser/_internal/csv_converter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from typing import List
from typing import Any, Dict, List


def csv_to_json(input: str, headers_included: bool = False) -> str:
Expand All @@ -18,3 +18,12 @@ def csv_to_json(input: str, headers_included: bool = False) -> str:
if output.endswith("\n"):
output = output.rstrip("\n")
return output


def json_to_csv(input: List[Dict[str, Any]], field_delimiter, record_delimiter) -> str:
result = ""
for row in input:
result += (
field_delimiter.join([f"{v}" for v in row.values()]) + record_delimiter
)
return result
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "py-partiql-parser"
version = "0.5.1"
version = "0.5.2"
description = "Pure Python PartiQL Parser"
readme = "README.md"
keywords = ["pypartiql", "parser"]
Expand Down
17 changes: 16 additions & 1 deletion tests/test_csv_converter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from py_partiql_parser._internal.csv_converter import csv_to_json
from py_partiql_parser import csv_to_json, json_to_csv
import json


Expand Down Expand Up @@ -37,3 +37,18 @@ def test_csv_to_json_with_headers() -> None:

line2 = json.loads(lines[2])
assert line2["City"] == "Seattle"


def test_json_to_csv() -> None:
json_result = csv_to_json(input_csv)
lines = json_result.split("\n")

csv_result = json_to_csv(
[json.loads(lines[0])], field_delimiter=",", record_delimiter="\n"
)
assert csv_result == "Sam,(949) 555-6701,Irvine,Solutions Architect\n"

csv_result = json_to_csv(
[json.loads(lines[4])], field_delimiter=",", record_delimiter="\n"
)
assert csv_result == "Sean,(949) 555-6705,Chicago,Developer\n"

0 comments on commit 4249dc0

Please sign in to comment.