Skip to content

Commit

Permalink
add delimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
adasium committed Mar 5, 2024
1 parent 573b4cb commit 146a885
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions bin/chom_json2csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@
DELIM = ','


def _columns(string: str) -> list[str] | None:
def _columns(string: str) -> list[str]:
chunks = string.split(',')
return [chunk.strip() for chunk in chunks]


def _delimiter(string: str) -> str:
string = string.replace('\\t', '\t').replace('tab', '\t')
return string


class FormatInfo(NamedTuple):
column: str
type: str
Expand Down Expand Up @@ -115,12 +120,14 @@ def _inner():

def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', required=False, action='store_true')
parser.add_argument('-D', '--debug', required=False, action='store_true')
parser.add_argument('-c', '--columns', required=False, type=_columns)
parser.add_argument('-f', '--format', required=False, type=_format)
parser.add_argument('-s', '--sort', required=False, type=_sort)
parser.add_argument('-d', '--delimiter', required=False, type=_delimiter)

args = parser.parse_args()
delimiter = args.delimiter or ','
if args.debug:
print(args.columns)
data = json.load(sys.stdin, object_pairs_hook=collections.OrderedDict)
Expand All @@ -129,7 +136,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
json_fields = list(dict.fromkeys(json_fields + list(doc.keys())))

csv_columns = args.columns or json_fields
print(','.join(csv_columns))
print(delimiter.join(csv_columns))

for sort_by in reversed(args.sort or []):
data = sorted(
Expand All @@ -139,7 +146,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
)

for doc in data:
line = ','.join(
line = delimiter.join(
format_output_item(
key=col,
value=doc[col],
Expand Down

0 comments on commit 146a885

Please sign in to comment.