Skip to content

Commit ed8f1c2

Browse files
thbarmichalmuskala
authored andcommitted
Document Jason.Fragment (#166)
* Add a test * Document Jason.Fragment * Add something in the readme
1 parent 0b54829 commit ed8f1c2

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,20 @@ Protocol.derive(Jason.Encoder, NameOfTheStruct, only: [...])
135135
Protocol.derive(Jason.Encoder, NameOfTheStruct)
136136
```
137137

138+
## Injecting an already encoded JSON inside a to-be-encoded structure
139+
140+
If parts of the to-be-encoded structure are already JSON-encoded, you can
141+
use `Jason.Fragment` to mark the parts as already encoded, and avoid a
142+
decoding/encoding roundtrip.
143+
144+
```elixir
145+
already_encoded_json = Jason.encode!(%{hello: "world"})
146+
Jason.encode!(%{foo: Jason.Fragment.new(already_encoded_json)})
147+
````
148+
149+
This feature is especially useful if you need to cache a part of the JSON,
150+
or if it is already provided by another system (e.g. `jsonb_agg` with Postgres).
151+
138152
## License
139153

140154
Jason is released under the Apache License 2.0 - see the [LICENSE](LICENSE) file.

lib/fragment.ex

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
defmodule Jason.Fragment do
2+
@moduledoc ~S"""
3+
Provides a way to inject an already-encoded JSON structure into a
4+
to-be-encoded structure in optimized fashion.
5+
6+
This avoids a decoding/encoding round-trip for the subpart.
7+
8+
This feature can be used for caching parts of the JSON, or delegating
9+
the generation of the JSON to a third-party system (e.g. Postgres).
10+
"""
11+
212
defstruct [:encode]
313

414
def new(iodata) when is_list(iodata) or is_binary(iodata) do

test/encode_test.exs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,11 @@ defmodule Jason.EncoderTest do
115115
assert to_json(multi_key_map) == ~s({"foo":"foo1","foo":"foo2"})
116116
end
117117

118+
test "Fragment" do
119+
pre_encoded_json = Jason.encode!(%{hello: "world", test: 123})
120+
assert to_json(%{foo: Jason.Fragment.new(pre_encoded_json)}) == ~s({"foo":{"hello":"world","test":123}})
121+
end
122+
118123
defmodule Derived do
119124
@derive Encoder
120125
defstruct name: ""

0 commit comments

Comments
 (0)