Elixir:
Working with JSON
How to:
In Elixir, you can use the Jason
library, a popular choice for JSON parsing and generation. First, add Jason
to your project’s dependencies in mix.exs
:
defp deps do
[
{:jason, "~> 1.3"}
]
end
Then, run mix deps.get
to fetch the dependency.
Parsing JSON:
To convert a JSON string into Elixir data structures:
json_string = "{\"name\":\"John\", \"age\":30}"
{:ok, person} = Jason.decode(json_string)
IO.inspect(person)
# Output: %{"name" => "John", "age" => 30}
Generating JSON:
To convert an Elixir map into a JSON string:
person_map = %{"name" => "Jane", "age" => 25}
{:ok, json_string} = Jason.encode(person_map)
IO.puts(json_string)
# Output: {"age":25,"name":"Jane"}
Working with Structs:
To encode an Elixir struct, you must implement the Jason.Encoder
protocol for your struct. Here’s an example:
defmodule Person do
@derive {Jason.Encoder, only: [:name, :age]}
defstruct name: nil, age: nil
end
person_struct = %Person{name: "Mike", age: 28}
{:ok, json_string} = Jason.encode(person_struct)
IO.puts(json_string)
# Output: {"age":28,"name":"Mike"}
This simple approach will get you started on integrating JSON processing into your Elixir applications, facilitating data interchange in various programming environments.