Skip to content

Commit

Permalink
Document Jason.Fragment (#166)
Browse files Browse the repository at this point in the history
* Add a test

* Document Jason.Fragment

* Add something in the readme
  • Loading branch information
thbar authored and michalmuskala committed Jul 7, 2023
1 parent 0b54829 commit ed8f1c2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
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

0 comments on commit ed8f1c2

Please sign in to comment.