

Jason — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/README.md#L1 "View Source")

Jason

===============================================================================================================

A blazing fast JSON parser and generator in pure Elixir.

The parser and generator are at least twice as fast as other Elixir/Erlang libraries

(most notably `Poison`).

The performance is comparable to `jiffy`, which is implemented in C as a NIF.

Jason is usually only twice as slow.

Both parser and generator fully conform to

[RFC 8259](https://tools.ietf.org/html/rfc8259) and

[ECMA 404](http://www.ecma-international.org/publications/standards/Ecma-404.htm)

standards. The parser is tested using [JSONTestSuite](https://github.com/nst/JSONTestSuite).

[installation](#installation)

 Installation

--------------------------------------------

The package can be installed by adding `jason` to your list of dependencies

in `mix.exs`:

```

def deps do

 [{:jason, "~> 1.4"}]

end

```

[basic-usage](#basic-usage)

 Basic Usage

-----------------------------------------

```

iex(1)> Jason.encode!(%{"age" => 44, "name" => "Steve Irwin", "nationality" => "Australian"})

"{\"age\":44,\"name\":\"Steve Irwin\",\"nationality\":\"Australian\"}"

iex(2)> Jason.decode!(~s({"age":44,"name":"Steve Irwin","nationality":"Australian"}))

%{"age" => 44, "name" => "Steve Irwin", "nationality" => "Australian"}

```

Full documentation can be found at <https://hexdocs.pm/jason>.

[use-with-other-libraries](#use-with-other-libraries)

 Use with other libraries

--------------------------------------------------------------------------------

### 

[postgrex](#postgrex)

 Postgrex

Versions starting at 0.14.0 use [`Jason`](Jason.html) by default. For earlier versions, please refer to

[previous versions of this document](https://github.com/michalmuskala/jason/tree/v1.1.2#postgrex).

### 

[ecto](#ecto)

 Ecto

Versions starting at 3.0.0 use [`Jason`](Jason.html) by default. For earlier versions, please refer to

[previous versions of this document](https://github.com/michalmuskala/jason/tree/v1.1.2#ecto).

### 

[plug-and-phoenix](#plug-and-phoenix)

 Plug (and Phoenix)

Phoenix starting at 1.4.0 uses [`Jason`](Jason.html) by default. For earlier versions, please refer to

[previous versions of this document](https://github.com/michalmuskala/jason/tree/v1.1.2#plug-and-phoenix).

### 

[absinthe](#absinthe)

 Absinthe

You need to pass the `:json_codec` option to `Absinthe.Plug`

```

# When called directly:

plug Absinthe.Plug,

 schema: MyApp.Schema,

 json\_codec: Jason

# When used in phoenix router:

forward "/api",

 to: Absinthe.Plug,

 init\_opts: [schema: MyApp.Schema, json\_codec: Jason]

```

[benchmarks](#benchmarks)

 Benchmarks

--------------------------------------

Detailed benchmarks (including memory measurements):

<https://gist.github.com/michalmuskala/4d64a5a7696ca84ac7c169a0206640d5>

HTML reports for the benchmark (only performance measurements):

<http://michal.muskala.eu/jason/decode.html> and <http://michal.muskala.eu/jason/encode.html>

### 

[running](#running)

 Running

Benchmarks against most popular Elixir & Erlang json libraries can be executed after

going into the `bench/` folder and then executing `mix bench.encode` and `mix bench.decode`.

A HTML report of the benchmarks (after their execution) can be found in

`bench/output/encode.html` and `bench/output/decode.html` respectively.

[differences-to-poison](#differences-to-poison)

 Differences to Poison

-----------------------------------------------------------------------

Jason has a couple feature differences compared to Poison.

* Jason follows the JSON spec more strictly, for example it does not allow

unescaped newline characters in JSON strings - e.g. `"\"\n\""` will

produce a decoding error.

* no support for decoding into data structures (the `as:` option).

* no built-in encoders for [`MapSet`](https://hexdocs.pm/elixir/MapSet.html), [`Range`](https://hexdocs.pm/elixir/Range.html) and [`Stream`](https://hexdocs.pm/elixir/Stream.html).

* no support for encoding arbitrary structs - explicit implementation

of the [`Jason.Encoder`](Jason.Encoder.html) protocol is always required.

* different pretty-printing customisation options (default `pretty: true` works the same)

### 

[encoders](#encoders)

 Encoders

If you require encoders for any of the unsupported collection types, I suggest

adding the needed implementations directly to your project:

```

defimpl Jason.Encoder, for: [MapSet, Range, Stream] do

 def encode(struct, opts) do

 Jason.Encode.list(Enum.to\_list(struct), opts)

 end

end

```

If you need to encode some struct that does not implement the protocol,

if you own the struct, you can derive the implementation specifying

which fields should be encoded to JSON:

```

@derive {Jason.Encoder, only: [....]}

defstruct # ...

```

It is also possible to encode all fields, although this should be

used carefully to avoid accidentally leaking private information

when new fields are added:

```

@derive Jason.Encoder

defstruct # ...

```

Finally, if you don't own the struct you want to encode to JSON,

you may use [`Protocol.derive/3`](https://hexdocs.pm/elixir/Protocol.html#derive/3) placed outside of any module:

```

Protocol.derive(Jason.Encoder, NameOfTheStruct, only: [...])

Protocol.derive(Jason.Encoder, NameOfTheStruct)

```

[injecting-an-already-encoded-json-inside-a-to-be-encoded-structure](#injecting-an-already-encoded-json-inside-a-to-be-encoded-structure)

 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`](Jason.Fragment.html) to mark the parts as already encoded, and avoid a

decoding/encoding roundtrip.

```

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.

Some elements of tests and benchmarks have their origins in the

[Poison library](https://github.com/devinus/poison) and were initially licensed under [CC0-1.0](https://creativecommons.org/publicdomain/zero/1.0/).

```

[← Previous Page

 

API Reference](api-reference.html)

[Next Page →

 

Changelog](changelog.html)





Jason — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L1 "View Source")

Jason

(jason v1.4.1)

=================================================================================================================================

A blazing fast JSON parser and generator in pure Elixir.

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[decode\_opt()](#t:decode_opt/0)

[encode\_opt()](#t:encode_opt/0)

[escape()](#t:escape/0)

[floats()](#t:floats/0)

[keys()](#t:keys/0)

[maps()](#t:maps/0)

[objects()](#t:objects/0)

[strings()](#t:strings/0)

[Functions](#functions)

------------------------

[decode!(input, opts \\ [])](#decode!/2)

Parses a JSON value from `input` iodata.

[decode(input, opts \\ [])](#decode/2)

Parses a JSON value from `input` iodata.

[encode!(input, opts \\ [])](#encode!/2)

Generates JSON corresponding to `input`.

[encode(input, opts \\ [])](#encode/2)

Generates JSON corresponding to `input`.

[encode\_to\_iodata!(input, opts \\ [])](#encode_to_iodata!/2)

Generates JSON corresponding to `input` and returns iodata.

[encode\_to\_iodata(input, opts \\ [])](#encode_to_iodata/2)

Generates JSON corresponding to `input` and returns iodata.

[Link to this section](#types)

Types

=====================================

[Link to this type](#t:decode_opt/0 "Link to this type")

decode\_opt()

=============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L21 "View Source")

```

@type decode_opt() ::

  {:keys, [keys](#t:keys/0)()}

  | {:strings, [strings](#t:strings/0)()}

  | {:floats, [floats](#t:floats/0)()}

  | {:objects, [objects](#t:objects/0)()}

```

[Link to this type](#t:encode_opt/0 "Link to this type")

encode\_opt()

=============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L11 "View Source")

```

@type encode_opt() ::

  {:escape, [escape](#t:escape/0)()}

  | {:maps, [maps](#t:maps/0)()}

  | {:pretty, [boolean](https://hexdocs.pm/elixir/typespecs.html#built-in-types)() | [Jason.Formatter.opts](Jason.Formatter.html#t:opts/0)()}

```

[Link to this type](#t:escape/0 "Link to this type")

escape()

========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L8 "View Source")

```

@type escape() :: :json | :unicode_safe | :html_safe | :javascript_safe

```

[Link to this type](#t:floats/0 "Link to this type")

floats()

========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L17 "View Source")

```

@type floats() :: :native | :decimals

```

[Link to this type](#t:keys/0 "Link to this type")

keys()

======

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L13 "View Source")

```

@type keys() :: :atoms | :atoms! | :strings | :copy | ([String.t](https://hexdocs.pm/elixir/String.html#t:t/0)() -> [term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)())

```

[Link to this type](#t:maps/0 "Link to this type")

maps()

======

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L9 "View Source")

```

@type maps() :: :naive | :strict

```

[Link to this type](#t:objects/0 "Link to this type")

objects()

=========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L19 "View Source")

```

@type objects() :: :maps | :ordered_objects

```

[Link to this type](#t:strings/0 "Link to this type")

strings()

=========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L15 "View Source")

```

@type strings() :: :reference | :copy

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#decode!/2 "Link to this function")

decode!(input, opts \\ [])

==========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L89 "View Source")

```

@spec decode!([iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [[decode\_opt](#t:decode_opt/0)()]) :: [term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)() | [no\_return](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Parses a JSON value from `input` iodata.

Similar to [`decode/2`](#decode/2) except it will unwrap the error tuple and raise

in case of errors.

[examples](#decode!/2-examples)

 Examples

------------------------------------------

```

iex> Jason.decode!("{}")

%{}

iex> Jason.decode!("invalid")

\*\* (Jason.DecodeError) unexpected byte at position 0: 0x69 ("i")

```

[Link to this function](#decode/2 "Link to this function")

decode(input, opts \\ [])

=========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L68 "View Source")

```

@spec decode([iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [[decode\_opt](#t:decode_opt/0)()]) ::

  {:ok, [term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()} | {:error, [Jason.DecodeError.t](Jason.DecodeError.html#t:t/0)()}

```

Parses a JSON value from `input` iodata.

[options](#decode/2-options)

 Options

--------------------------------------

* `:keys` - controls how keys in objects are decoded. Possible values are:

	+ `:strings` (default) - decodes keys as binary strings,

	+ `:atoms` - keys are converted to atoms using [`String.to_atom/1`](https://hexdocs.pm/elixir/String.html#to_atom/1),

	+ `:atoms!` - keys are converted to atoms using [`String.to_existing_atom/1`](https://hexdocs.pm/elixir/String.html#to_existing_atom/1),

	+ custom decoder - additionally a function accepting a string and returning a key

	is accepted.

* `:strings` - controls how strings (including keys) are decoded. Possible values are:

	+ `:reference` (default) - when possible tries to create a sub-binary into the original

	+ `:copy` - always copies the strings. This option is especially useful when parts of the

	decoded data will be stored for a long time (in ets or some process) to avoid keeping

	the reference to the original data.

* `:floats` - controls how floats are decoded. Possible values are:

	+ `:native` (default) - Native conversion from binary to float using [`:erlang.binary_to_float/1`](https://www.erlang.org/doc/man/erlang.html#binary_to_float-1),

	+ `:decimals` - uses [`Decimal.new/1`](https://hexdocs.pm/decimal/2.0.0/Decimal.html#new/1) to parse the binary into a Decimal struct with arbitrary precision.

* `:objects` - controls how objects are decoded. Possible values are:

	+ `:maps` (default) - objects are decoded as maps

	+ `:ordered_objects` - objects are decoded as [`Jason.OrderedObject`](Jason.OrderedObject.html) structs

[decoding-keys-to-atoms](#decode/2-decoding-keys-to-atoms)

 Decoding keys to atoms

-----------------------------------------------------------------------------------

The `:atoms` option uses the [`String.to_atom/1`](https://hexdocs.pm/elixir/String.html#to_atom/1) call that can create atoms at runtime.

Since the atoms are not garbage collected, this can pose a DoS attack vector when used

on user-controlled data.

[examples](#decode/2-examples)

 Examples

-----------------------------------------

```

iex> Jason.decode("{}")

{:ok, %{}}

iex> Jason.decode("invalid")

{:error, %Jason.DecodeError{data: "invalid", position: 0, token: nil}}

```

[Link to this function](#encode!/2 "Link to this function")

encode!(input, opts \\ [])

==========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L161 "View Source")

```

@spec encode!([term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [[encode\_opt](#t:encode_opt/0)()]) :: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)() | [no\_return](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Generates JSON corresponding to `input`.

Similar to [`encode/1`](#encode/1) except it will unwrap the error tuple and raise

in case of errors.

[examples](#encode!/2-examples)

 Examples

------------------------------------------

```

iex> Jason.encode!(%{a: 1})

~S|{"a":1}|

iex> Jason.encode!("\xFF")

\*\* (Jason.EncodeError) invalid byte 0xFF in <<255>>

```

[Link to this function](#encode/2 "Link to this function")

encode(input, opts \\ [])

=========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L138 "View Source")

```

@spec encode([term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [[encode\_opt](#t:encode_opt/0)()]) ::

  {:ok, [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()} | {:error, [Jason.EncodeError.t](Jason.EncodeError.html#t:t/0)() | [Exception.t](https://hexdocs.pm/elixir/Exception.html#t:t/0)()}

```

Generates JSON corresponding to `input`.

The generation is controlled by the [`Jason.Encoder`](Jason.Encoder.html) protocol,

please refer to the module to read more on how to define the protocol

for custom data types.

[options](#encode/2-options)

 Options

--------------------------------------

* `:escape` - controls how strings are encoded. Possible values are:

	+ `:json` (default) - the regular JSON escaping as defined by RFC 7159.

	+ `:javascript_safe` - additionally escapes the LINE SEPARATOR (U+2028)

	and PARAGRAPH SEPARATOR (U+2029) characters to make the produced JSON

	valid JavaScript.

	+ `:html_safe` - similar to `:javascript_safe`, but also escapes the `/`

	character to prevent XSS.

	+ `:unicode_safe` - escapes all non-ascii characters.

* `:maps` - controls how maps are encoded. Possible values are:

	+ `:strict` - checks the encoded map for duplicate keys and raises

	if they appear. For example `%{:foo => 1, "foo" => 2}` would be

	rejected, since both keys would be encoded to the string `"foo"`.

	+ `:naive` (default) - does not perform the check.

* `:pretty` - controls pretty printing of the output. Possible values are:

	+ `true` to pretty print with default configuration

	+ a keyword of options as specified by [`Jason.Formatter.pretty_print/2`](Jason.Formatter.html#pretty_print/2).

[examples](#encode/2-examples)

 Examples

-----------------------------------------

```

iex> Jason.encode(%{a: 1})

{:ok, ~S|{"a":1}|}

iex> Jason.encode("\xFF")

{:error, %Jason.EncodeError{message: "invalid byte 0xFF in <<255>>"}}

```

[Link to this function](#encode_to_iodata!/2 "Link to this function")

encode\_to\_iodata!(input, opts \\ [])

======================================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L210 "View Source")

```

@spec encode_to_iodata!([term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [[encode\_opt](#t:encode_opt/0)()]) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)() | [no\_return](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Generates JSON corresponding to `input` and returns iodata.

Similar to [`encode_to_iodata/1`](#encode_to_iodata/1) except it will unwrap the error tuple

and raise in case of errors.

[examples](#encode_to_iodata!/2-examples)

 Examples

----------------------------------------------------

```

iex> iodata = Jason.encode\_to\_iodata!(%{a: 1})

iex> IO.iodata\_to\_binary(iodata)

~S|{"a":1}|

iex> Jason.encode\_to\_iodata!("\xFF")

\*\* (Jason.EncodeError) invalid byte 0xFF in <<255>>

```

[Link to this function](#encode_to_iodata/2 "Link to this function")

encode\_to\_iodata(input, opts \\ [])

=====================================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/jason.ex#L189 "View Source")

```

@spec encode_to_iodata([term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [[encode\_opt](#t:encode_opt/0)()]) ::

  {:ok, [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()} | {:error, [Jason.EncodeError.t](Jason.EncodeError.html#t:t/0)() | [Exception.t](https://hexdocs.pm/elixir/Exception.html#t:t/0)()}

```

Generates JSON corresponding to `input` and returns iodata.

This function should be preferred to [`encode/2`](#encode/2), if the generated

JSON will be handed over to one of the IO functions or sent

over the socket. The Erlang runtime is able to leverage vectorised

writes and avoid allocating a continuous buffer for the whole

resulting string, lowering memory use and increasing performance.

[examples](#encode_to_iodata/2-examples)

 Examples

---------------------------------------------------

```

iex> {:ok, iodata} = Jason.encode\_to\_iodata(%{a: 1})

iex> IO.iodata\_to\_binary(iodata)

~S|{"a":1}|

iex> Jason.encode\_to\_iodata("\xFF")

{:error, %Jason.EncodeError{message: "invalid byte 0xFF in <<255>>"}}

```





Jason.DecodeError — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/decoder.ex#L1 "View Source")

Jason.DecodeError exception

(jason v1.4.1)

=========================================================================================================================================================

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[t()](#t:t/0)

[Functions](#functions)

------------------------

[message(map)](#message/1)

Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).

[Link to this section](#types)

Types

=====================================

[Link to this type](#t:t/0 "Link to this type")

t()

===

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/decoder.ex#L2 "View Source")

```

@type t() :: %Jason.DecodeError{

  __exception__: true,

  data: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(),

  position: [integer](https://hexdocs.pm/elixir/typespecs.html#basic-types)(),

  token: [term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

}

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#message/1 "Link to this function")

message(map)

============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/decoder.ex#L6 "View Source")

Callback implementation for [`Exception.message/1`](https://hexdocs.pm/elixir/Exception.html#c:message/1).





Jason.Encode — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L14 "View Source")

Jason.Encode

(jason v1.4.1)

==========================================================================================================================================

Utilities for encoding elixir values to JSON.

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[opts()](#t:opts/0)

[Functions](#functions)

------------------------

[atom(atom, arg)](#atom/2)

[float(float)](#float/1)

[integer(integer)](#integer/1)

[keyword(list, arg2)](#keyword/2)

[list(list, arg)](#list/2)

[map(value, arg)](#map/2)

[string(string, arg)](#string/2)

[struct(value, arg)](#struct/2)

[value(value, arg)](#value/2)

Equivalent to calling the [`Jason.Encoder.encode/2`](Jason.Encoder.html#encode/2) protocol function.

[Link to this section](#types)

Types

=====================================

[Link to this opaque](#t:opts/0 "Link to this opaque")

opts()

======

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L25 "View Source")

(opaque)

```

@opaque opts()

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#atom/2 "Link to this function")

atom(atom, arg)

===============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L115 "View Source")

```

@spec atom([atom](https://hexdocs.pm/elixir/typespecs.html#basic-types)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#float/1 "Link to this function")

float(float)

============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L140 "View Source")

```

@spec float([float](https://hexdocs.pm/elixir/typespecs.html#basic-types)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#integer/1 "Link to this function")

integer(integer)

================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L126 "View Source")

```

@spec integer([integer](https://hexdocs.pm/elixir/typespecs.html#basic-types)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#keyword/2 "Link to this function")

keyword(list, arg2)

===================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L173 "View Source")

```

@spec keyword(

  [keyword](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(),

  [opts](#t:opts/0)()

) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#list/2 "Link to this function")

list(list, arg)

===============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L150 "View Source")

```

@spec list([list](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#map/2 "Link to this function")

map(value, arg)

===============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L179 "View Source")

```

@spec map([map](https://hexdocs.pm/elixir/typespecs.html#basic-types)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#string/2 "Link to this function")

string(string, arg)

===================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L276 "View Source")

```

@spec string([String.t](https://hexdocs.pm/elixir/String.html#t:t/0)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#struct/2 "Link to this function")

struct(value, arg)

==================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L228 "View Source")

```

@spec struct(

  [struct](https://hexdocs.pm/elixir/typespecs.html#basic-types)(),

  [opts](#t:opts/0)()

) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this function](#value/2 "Link to this function")

value(value, arg)

=================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L71 "View Source")

```

@spec value([term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Equivalent to calling the [`Jason.Encoder.encode/2`](Jason.Encoder.html#encode/2) protocol function.

Slightly more efficient for built-in types because of the internal dispatching.





Jason.EncodeError — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L1 "View Source")

Jason.EncodeError exception

(jason v1.4.1)

========================================================================================================================================================

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[t()](#t:t/0)

[Functions](#functions)

------------------------

[new(arg)](#new/1)

[Link to this section](#types)

Types

=====================================

[Link to this type](#t:t/0 "Link to this type")

t()

===

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L4 "View Source")

```

@type t() :: %Jason.EncodeError{__exception__: true, message: [String.t](https://hexdocs.pm/elixir/String.html#t:t/0)()}

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#new/1 "Link to this function")

new(arg)

========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encode.ex#L6 "View Source")





Jason.Encoder — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encoder.ex#L1 "View Source")

Jason.Encoder protocol

(jason v1.4.1)

====================================================================================================================================================

Protocol controlling how a value is encoded to JSON.

[deriving](#module-deriving)

 Deriving

---------------------------------------

The protocol allows leveraging the Elixir's `@derive` feature

to simplify protocol implementation in trivial cases. Accepted

options are:

* `:only` - encodes only values of specified keys.

* `:except` - encodes all struct fields except specified keys.

By default all keys except the `:__struct__` key are encoded.

[example](#module-example)

 Example

------------------------------------

Let's assume a presence of the following struct:

```

defmodule Test do

 defstruct [:foo, :bar, :baz]

end

```

If we were to call `@derive Jason.Encoder` just before `defstruct`,

an implementation similar to the following implementation would be generated:

```

defimpl Jason.Encoder, for: Test do

 def encode(value, opts) do

 Jason.Encode.map(Map.take(value, [:foo, :bar, :baz]), opts)

 end

end

```

If we called `@derive {Jason.Encoder, only: [:foo]}`, an implementation

similar to the following implementation would be generated:

```

defimpl Jason.Encoder, for: Test do

 def encode(value, opts) do

 Jason.Encode.map(Map.take(value, [:foo]), opts)

 end

end

```

If we called `@derive {Jason.Encoder, except: [:foo]}`, an implementation

similar to the following implementation would be generated:

```

defimpl Jason.Encoder, for: Test do

 def encode(value, opts) do

 Jason.Encode.map(Map.take(value, [:bar, :baz]), opts)

 end

end

```

The actually generated implementations are more efficient computing some data

during compilation similar to the macros from the [`Jason.Helpers`](Jason.Helpers.html) module.

[explicit-implementation](#module-explicit-implementation)

 Explicit implementation

------------------------------------------------------------------------------------

If you wish to implement the protocol fully yourself, it is advised to

use functions from the [`Jason.Encode`](Jason.Encode.html) module to do the actual iodata

generation - they are highly optimized and verified to always produce

valid JSON.

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[opts()](#t:opts/0)

[t()](#t:t/0)

[Functions](#functions)

------------------------

[encode(value, opts)](#encode/2)

Encodes `value` to JSON.

[Link to this section](#types)

Types

=====================================

[Link to this type](#t:opts/0 "Link to this type")

opts()

======

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encoder.ex#L63 "View Source")

```

@type opts() :: [Jason.Encode.opts](Jason.Encode.html#t:opts/0)()

```

[Link to this type](#t:t/0 "Link to this type")

t()

===

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encoder.ex#L62 "View Source")

```

@type t() :: [term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#encode/2 "Link to this function")

encode(value, opts)

===================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/encoder.ex#L74 "View Source")

```

@spec encode([t](#t:t/0)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Encodes `value` to JSON.

The argument `opts` is opaque - it can be passed to various functions in

[`Jason.Encode`](Jason.Encode.html) (or to the protocol function itself) for encoding values to JSON.





Jason.Formatter — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/formatter.ex#L1 "View Source")

Jason.Formatter

(jason v1.4.1)

===============================================================================================================================================

Pretty-printing and minimizing functions for JSON-encoded data.

Input is required to be in an 8-bit-wide encoding such as UTF-8 or Latin-1

in [`iodata/0`](https://hexdocs.pm/elixir/typespecs.html#built-in-types) format. Input must have valid JSON, invalid JSON may produce

unexpected results or errors.

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[opts()](#t:opts/0)

[Functions](#functions)

------------------------

[minimize(input, opts \\ [])](#minimize/2)

Minimizes JSON-encoded `input`.

[minimize\_to\_iodata(input, opts)](#minimize_to_iodata/2)

Minimizes JSON-encoded `input` and returns iodata.

[pretty\_print(input, opts \\ [])](#pretty_print/2)

Pretty-prints JSON-encoded `input`.

[pretty\_print\_to\_iodata(input, opts \\ [])](#pretty_print_to_iodata/2)

Pretty-prints JSON-encoded `input` and returns iodata.

[Link to this section](#types)

Types

=====================================

[Link to this type](#t:opts/0 "Link to this type")

opts()

======

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/formatter.ex#L10 "View Source")

```

@type opts() :: [

  indent: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(),

  line_separator: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(),

  record_separator: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(),

  after_colon: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

]

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#minimize/2 "Link to this function")

minimize(input, opts \\ [])

===========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/formatter.ex#L96 "View Source")

```

@spec minimize([iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [opts](#t:opts/0)()) :: [binary](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Minimizes JSON-encoded `input`.

`input` may contain multiple JSON objects or arrays, optionally

separated by whitespace (e.g., one object per line). Minimized

output will contain one object per line. No trailing newline is emitted.

[options](#minimize/2-options)

 Options

----------------------------------------

* `:record_separator` - controls the string used as newline (default: `"\n"`).

[examples](#minimize/2-examples)

 Examples

-------------------------------------------

```

iex> Jason.Formatter.minimize(~s|{ "a" : "b" , "c": \n\n 2}|)

~s|{"a":"b","c":2}|

```

[Link to this function](#minimize_to_iodata/2 "Link to this function")

minimize\_to\_iodata(input, opts)

=================================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/formatter.ex#L112 "View Source")

```

@spec minimize_to_iodata([iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Minimizes JSON-encoded `input` and returns iodata.

This function should be preferred to [`minimize/2`](#minimize/2), if the minimized

JSON will be handed over to one of the IO functions or sent

over the socket. The Erlang runtime is able to leverage vectorised

writes and avoid allocating a continuous buffer for the whole

resulting string, lowering memory use and increasing performance.

[Link to this function](#pretty_print/2 "Link to this function")

pretty\_print(input, opts \\ [])

================================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/formatter.ex#L51 "View Source")

```

@spec pretty_print([iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [opts](#t:opts/0)()) :: [binary](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Pretty-prints JSON-encoded `input`.

`input` may contain multiple JSON objects or arrays, optionally separated

by whitespace (e.g., one object per line). Objects in output will be

separated by newlines. No trailing newline is emitted.

[options](#pretty_print/2-options)

 Options

--------------------------------------------

* `:indent` - used for nested objects and arrays (default: two spaces - `" "`);

* `:line_separator` - used in nested objects (default: `"\n"`);

* `:record_separator` - separates root-level objects and arrays

(default is the value for `:line_separator` option);

* `:after_colon` - printed after a colon inside objects (default: one space - `" "`).

[examples](#pretty_print/2-examples)

 Examples

-----------------------------------------------

```

iex> Jason.Formatter.pretty\_print(~s|{"a":{"b": [1, 2]}}|)

~s|{

 "a": {

 "b": [

 1,

 2

 ]

 }

}|

```

[Link to this function](#pretty_print_to_iodata/2 "Link to this function")

pretty\_print\_to\_iodata(input, opts \\ [])

============================================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/formatter.ex#L67 "View Source")

```

@spec pretty_print_to_iodata([iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)(), [opts](#t:opts/0)()) :: [iodata](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()

```

Pretty-prints JSON-encoded `input` and returns iodata.

This function should be preferred to [`pretty_print/2`](#pretty_print/2), if the pretty-printed

JSON will be handed over to one of the IO functions or sent

over the socket. The Erlang runtime is able to leverage vectorised

writes and avoid allocating a continuous buffer for the whole

resulting string, lowering memory use and increasing performance.





Jason.Fragment — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/fragment.ex#L1 "View Source")

Jason.Fragment

(jason v1.4.1)

=============================================================================================================================================

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).

[Link to this section](#summary)

 Summary

==========================================

[Functions](#functions)

------------------------

[new(iodata)](#new/1)

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#new/1 "Link to this function")

new(iodata)

===========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/fragment.ex#L14 "View Source")





Jason.Helpers — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/helpers.ex#L1 "View Source")

Jason.Helpers

(jason v1.4.1)

===========================================================================================================================================

Provides macro facilities for partial compile-time encoding of JSON.

[Link to this section](#summary)

 Summary

==========================================

[Functions](#functions)

------------------------

[json\_map(kv)](#json_map/1)

Encodes a JSON map from a compile-time keyword.

[json\_map\_take(map, take)](#json_map_take/2)

Encodes a JSON map from a variable containing a map and a compile-time

list of keys.

[Link to this section](#functions)

Functions

=============================================

[Link to this macro](#json_map/1 "Link to this macro")

json\_map(kv)

=============

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/helpers.ex#L32 "View Source")

(macro)

Encodes a JSON map from a compile-time keyword.

Encodes the keys at compile time and strives to create as flat iodata

structure as possible to achieve maximum efficiency. Does encoding

right at the call site, but returns an `%Jason.Fragment{}` struct

that needs to be passed to one of the "main" encoding functions -

for example [`Jason.encode/2`](Jason.html#encode/2) for final encoding into JSON - this

makes it completely transparent for most uses.

Only allows keys that do not require escaping in any of the supported

encoding modes. This means only ASCII characters from the range

0x1F..0x7F excluding '\', '/' and '"' are allowed - this also excludes

all control characters like newlines.

Preserves the order of the keys.

[example](#json_map/1-example)

 Example

----------------------------------------

```

iex> fragment = json\_map(foo: 1, bar: 2)

iex> Jason.encode!(fragment)

"{\"foo\":1,\"bar\":2}"

```

[Link to this macro](#json_map_take/2 "Link to this macro")

json\_map\_take(map, take)

==========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/helpers.ex#L70 "View Source")

(macro)

Encodes a JSON map from a variable containing a map and a compile-time

list of keys.

It is equivalent to calling [`Map.take/2`](https://hexdocs.pm/elixir/Map.html#take/2) before encoding. Otherwise works

similar to `json_map/2`.

[example](#json_map_take/2-example)

 Example

---------------------------------------------

```

iex> map = %{a: 1, b: 2, c: 3}

iex> fragment = json\_map\_take(map, [:c, :b])

iex> Jason.encode!(fragment)

"{\"c\":3,\"b\":2}"

```





Jason.OrderedObject — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/ordered_object.ex#L1 "View Source")

Jason.OrderedObject

(jason v1.4.1)

========================================================================================================================================================

[Link to this section](#summary)

 Summary

==========================================

[Types](#types)

----------------

[t()](#t:t/0)

[Functions](#functions)

------------------------

[%Jason.OrderedObject{}](#__struct__/0)

Struct implementing a JSON object retaining order of properties.

[new(values)](#new/1)

[Link to this section](#types)

Types

=====================================

[Link to this type](#t:t/0 "Link to this type")

t()

===

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/ordered_object.ex#L14 "View Source")

```

@type t() :: %Jason.OrderedObject{values: [{[String.Chars.t](https://hexdocs.pm/elixir/String.Chars.html#t:t/0)(), [term](https://hexdocs.pm/elixir/typespecs.html#built-in-types)()}]}

```

[Link to this section](#functions)

Functions

=============================================

[Link to this function](#__struct__/0 "Link to this function")

%Jason.OrderedObject{}

======================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/ordered_object.ex#L16 "View Source")

(struct)

Struct implementing a JSON object retaining order of properties.

A wrapper around a keyword (that supports non-atom keys) allowing for

proper protocol implementations.

Implements the [`Access`](https://hexdocs.pm/elixir/Access.html) behaviour and [`Enumerable`](https://hexdocs.pm/elixir/Enumerable.html) protocol with

complexity similar to keywords/lists.

[Link to this function](#new/1 "Link to this function")

new(values)

===========

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/ordered_object.ex#L18 "View Source")





Jason.Sigil — jason v1.4.1

 try {

 var settings = JSON.parse(localStorage.getItem('ex\_doc:settings') || '{}');

 if (settings.theme === 'dark' ||

 ((settings.theme === 'system' || settings.theme == null) &&

 window.matchMedia('(prefers-color-scheme: dark)').matches)

 ) {

 document.body.classList.add('dark')

 }

 } catch (error) { }

 

Settings

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/sigil.ex#L1 "View Source")

Jason.Sigil

(jason v1.4.1)

=======================================================================================================================================

[Link to this section](#summary)

 Summary

==========================================

[Functions](#functions)

------------------------

[sigil\_J(term, modifiers)](#sigil_J/2)

Handles the sigil `~J` for raw JSON strings.

[sigil\_j(term, modifiers)](#sigil_j/2)

Handles the sigil `~j` for JSON strings.

[Link to this section](#functions)

Functions

=============================================

[Link to this macro](#sigil_J/2 "Link to this macro")

sigil\_J(term, modifiers)

=========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/sigil.ex#L67 "View Source")

(macro)

Handles the sigil `~J` for raw JSON strings.

Decodes a raw string ignoring Elixir interpolations and

escape characters at compile-time.

[examples](#sigil_J/2-examples)

 Examples

------------------------------------------

```

iex> ~J'"#{string}"'

"\#{string}"

iex> ~J'"\u0078\\y"'

"x\\y"

iex> ~J'{"#{key}": "#{}"}'a

%{"\#{key}": "\#{}"}

```

[Link to this macro](#sigil_j/2 "Link to this macro")

sigil\_j(term, modifiers)

=========================

[View Source](https://github.com/michalmuskala/jason/blob/v1.4.1/lib/sigil.ex#L40 "View Source")

(macro)

Handles the sigil `~j` for JSON strings.

Calls [`Jason.decode!/2`](Jason.html#decode!/2) with modifiers mapped to options.

Given a string literal without interpolations, decodes the

string at compile-time.

[modifiers](#sigil_j/2-modifiers)

 Modifiers

---------------------------------------------

See [`Jason.decode/2`](Jason.html#decode/2) for detailed descriptions.

* `a` - equivalent to `{:keys, :atoms}` option

* `A` - equivalent to `{:keys, :atoms!}` option

* `r` - equivalent to `{:strings, :reference}` option

* `c` - equivalent to `{:strings, :copy}` option

[examples](#sigil_j/2-examples)

 Examples

------------------------------------------

```

iex> ~j"0"

0

iex> ~j"[1, 2, 3]"

[1, 2, 3]

iex> ~j'"string"'r

"string"

iex> ~j"{}"

%{}

iex> ~j'{"atom": "value"}'a

%{atom: "value"}

iex> ~j'{"#{:j}": #{'"j"'}}'A

%{j: "j"}

```

