Skip to content

Instantly share code, notes, and snippets.

@gecBurton
Created January 27, 2021 20:19
Show Gist options
  • Save gecBurton/f0a05e2d1a66e8d3e5fee814cea8fd1e to your computer and use it in GitHub Desktop.
Save gecBurton/f0a05e2d1a66e8d3e5fee814cea8fd1e to your computer and use it in GitHub Desktop.
import io
import json
from typing import Any, Dict, Iterator, List, Union
def _parse_row(row: str) -> List[Any]:
return json.loads(f"[{row}]")
def parse(file_io: io.TextIOWrapper, header: bool = True) -> Iterator[Union[Dict[str, Any], Any]]:
"""implements https://github.com/DrorHarari/csvjson"""
if header:
field_names = _parse_row(file_io.readline())
if all(isinstance(field_name, dict) for field_name in field_names):
field_names = [field["field"] for field in field_names]
elif not all(isinstance(field_name, str) for field_name in field_names):
raise ValueError()
while True:
line = file_io.readline().strip()
if not line:
break
field_values = _parse_row(line)
if header:
assert len(field_values) == len(field_names)
yield dict(zip(field_names, field_values))
else:
yield field_values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment