Skip to content
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

Add examples to jiter-python README #143

Merged
merged 5 commits into from
Sep 23, 2024
Merged
Changes from 2 commits
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
54 changes: 54 additions & 0 deletions crates/jiter-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,57 @@ def cache_usage() -> int:
Size of the string cache in bytes.
"""
```
## Examples

The main function provided by Jiter is `from_json()`, which accepts a bytes object containing JSON and returns a Python dictionary, list or other value.

```python
import jiter

json_data = b'{"name": "John", "age": 30}'
parsed_data = jiter.from_json(json_data)
print(parsed_data) # Output: {'name': 'John', 'age': 30}
```
### Handling Partial JSON
simonw marked this conversation as resolved.
Show resolved Hide resolved

Incomplete JSON objects can be parsed using the `partial_mode=` parameter.

```python
import jiter

partial_json = b'{"name": "John", "age": 30, "city": "New Yor'

# Raise error on incomplete JSON
try:
jiter.from_json(partial_json, partial_mode='off')
simonw marked this conversation as resolved.
Show resolved Hide resolved
except ValueError as e:
print(f"Error: {e}")

# Parse incomplete JSON, discarding incomplete last field
result = jiter.from_json(partial_json, partial_mode='on')
simonw marked this conversation as resolved.
Show resolved Hide resolved
print(result) # Output: {'name': 'John', 'age': 30}

# Parse incomplete JSON, including incomplete last field
result = jiter.from_json(partial_json, partial_mode='trailing-strings')
print(result) # Output: {'name': 'John', 'age': 30, 'city': 'New Yor'}
```

### Catching Duplicate Keys

The `catch_duplicate_keys=True` option can be used to raise a `ValueError` if an object contains duplicate keys.

```python
import jiter

json_with_dupes = b'{"foo": 1, "foo": 2}'

# Default behavior (last value wins)
result = jiter.from_json(json_with_dupes)
print(result) # Output: {'foo': 2}

# Catch duplicate keys
try:
jiter.from_json(json_with_dupes, catch_duplicate_keys=True)
except ValueError as e:
print(f"Error: {e}")
```
Loading