How to parse JSON with jason in elixir

The jason is a blazing-fast JSON parser and generator that’s written in pure Elixir.

The jason package can be installed by adding it to the dependencies list in mix.exs:

def deps do
  [{:jason, "~> 1.3"}]
end

JSON encoding

The jason.encode() function is used to generate a JSON corresponding to the given input.

Syntax

Jason.encode(input, opts \\ [])

Parameters

  • input: This is the input whose JSON has to be generated.
  • opts: These are the options for the function.

JSON decoding

The jason.decode() function is used to parse a JSON from the given input.

Syntax

Jason.decode(input, opts \\ [])

Parameters

  • input: This is the input to be parsed to a JSON.
  • opts: These are the options for the function.

Code example

Let’s look at the code below:

defp to_json(value, opts \\ []) do
Jason.encode!(value, opts)
end
defp parse!(json, opts \\ []) do
Jason.decode!(json, opts)
end
IO.puts to_json(%{a: 3.14159, b: 1}, pretty: true)
IO.puts parse!(~s( { "foo" : "bar" , "baz" : "quux" } ))

Code explanation

  • Lines 1-3: The to_json() function is defined where the json is encoded using the Jason.encode!() function.
  • Lines 5-7: The parse() function is defined where the json is decoded using the Jason.decode!() function.
  • Line 9: The to_json() function is invoked.
  • Line 11: The parse() function is invoked.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved