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

Document Jason.Fragment #166

Merged
merged 3 commits into from
May 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,20 @@ Protocol.derive(Jason.Encoder, NameOfTheStruct, only: [...])
Protocol.derive(Jason.Encoder, NameOfTheStruct)
```

## Injecting an already encoded JSON inside a to-be-encoded structure

If parts of the to-be-encoded structure are already JSON-encoded, you can
use `Jason.Fragment` to mark the parts as already encoded, and avoid a
decoding/encoding roundtrip.

```elixir
already_encoded_json = Jason.encode!(%{hello: "world"})
Jason.encode!(%{foo: Jason.Fragment.new(already_encoded_json)})
````

This feature is especially useful if you need to cache a part of the JSON,
or if it is already provided by another system (e.g. `jsonb_agg` with Postgres).

## License

Jason is released under the Apache License 2.0 - see the [LICENSE](LICENSE) file.
Expand Down
10 changes: 10 additions & 0 deletions lib/fragment.ex
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
defmodule Jason.Fragment do
@moduledoc ~S"""
Provides a way to inject an already-encoded JSON structure into a
to-be-encoded structure in optimized fashion.

This avoids a decoding/encoding round-trip for the subpart.

This feature can be used for caching parts of the JSON, or delegating
the generation of the JSON to a third-party system (e.g. Postgres).
"""

defstruct [:encode]

def new(iodata) when is_list(iodata) or is_binary(iodata) do
Expand Down
5 changes: 5 additions & 0 deletions test/encode_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ defmodule Jason.EncoderTest do
assert to_json(multi_key_map) == ~s({"foo":"foo1","foo":"foo2"})
end

test "Fragment" do
pre_encoded_json = Jason.encode!(%{hello: "world", test: 123})
assert to_json(%{foo: Jason.Fragment.new(pre_encoded_json)}) == ~s({"foo":{"hello":"world","test":123}})
end

defmodule Derived do
@derive Encoder
defstruct name: ""
Expand Down