diff --git a/README.md b/README.md index b0d2ae1..3f44066 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,14 @@ Yet another Json Parser for Python ### Supports -it supports standard libraries -- dump +it supports standard `json` lib's - dumps -- load - loads +- dump +- load + +functions -functionalities. ### loads examples ```python @@ -23,12 +24,26 @@ functionalities. >>> pyyjson.loads('[{"a":"b"}, 3, 4]') [{'a': 'b'}, 3, 4] ``` + ### dumps example ```python >>> pyyjson.dumps([{'a': 'b'}, 3, 4]) '[{"a":"b"},3,4]' ``` +### load example +```python +>>> import pyyjson +>>> pyyjson.load("simple_json.json") # in "tests/" directory +{'a': 1, 'b': 2, 'c': 3} +``` + +### dump example +```python +>>> import pyyjson +>>> pyyjson.dump({'a': 1, 'b': 2, 'c': 3}, "simple_json.json") +``` + ### Benchmarks each elements in cols denotes "calls/sec". Test suite is adapted from ujson's benchmark format. diff --git a/pyyjson/wrapper.py b/pyyjson/wrapper.py index 9c1e473..8fdf53b 100644 --- a/pyyjson/wrapper.py +++ b/pyyjson/wrapper.py @@ -1,4 +1,6 @@ import enum +import io +import os from pyyjson.cserde import _loads, _dumps from inspect import signature @@ -47,7 +49,13 @@ def loads(doc, flags=0x00): def load(fp, flags=0x00): - txt = fp.read() + if type(fp) == io.TextIOWrapper: + txt = fp.read() + elif type(fp) == str: + if not os.path.exists(fp): + raise FileNotFoundError(f"{fp} not found!") + with open(fp, 'r') as f: + txt = f.read() return loads(txt, flags) @@ -74,5 +82,12 @@ def dumps(obj, ensure_ascii=False, default=None, escape_slash=False, flags=0x00) def dump(obj, fp, ensure_ascii=False, default=None, escape_slash=False, flags=0x00): - ret_str = _dumps(obj, ensure_ascii=ensure_ascii, default=default, escape_slash=escape_slash, flags=flags) - return fp.write(ret_str) + ret_str = dumps(obj, ensure_ascii=ensure_ascii, default=default, escape_slash=escape_slash, flags=flags) + # return fp.write(ret_str) + if type(fp) == io.TextIOWrapper: + fp.write(ret_str) + elif type(fp) == str: + if not os.path.exists(fp): + raise FileNotFoundError(f"{fp} not found!") + with open(fp, 'w') as f: + f.write(ret_str) diff --git a/tests/simple_json.json b/tests/simple_json.json index 7878a20..4a972de 100644 --- a/tests/simple_json.json +++ b/tests/simple_json.json @@ -1,5 +1 @@ -{ - "a": 1, - "b": 2, - "c": 3 -} \ No newline at end of file +{"a":1,"b":2,"c":3} \ No newline at end of file