Git Product home page Git Product logo

poison's Introduction

Poison

Travis Hex.pm Hex.pm Gratipay

Poison is a new JSON library for Elixir focusing on wicked-fast speed without sacrificing simplicity, completeness, or correctness.

Poison takes several approaches to be the fastest JSON library for Elixir.

Poison uses extensive sub binary matching, a hand-rolled parser using several techniques that are known to benefit HiPE for native compilation, IO list encoding and single-pass decoding.

Preliminary benchmarking has sometimes put Poison's performance closer to jiffy, and almost always faster than existing Elixir libraries.

Installation

First, add Poison to your mix.exs dependencies:

def deps do
  [{:poison, "~> 3.0"}]
end

Then, update your dependencies:

$ mix deps.get

Usage

defmodule Person do
  @derive [Poison.Encoder]
  defstruct [:name, :age]
end

Poison.encode!(%Person{name: "Devin Torres", age: 27})
#=> "{\"name\":\"Devin Torres\",\"age\":27}"

Poison.decode!(~s({"name": "Devin Torres", "age": 27}), as: %Person{})
#=> %Person{name: "Devin Torres", age: 27}

Poison.decode!(~s({"people": [{"name": "Devin Torres", "age": 27}]}),
  as: %{"people" => [%Person{}]})
#=> %{"people" => [%Person{age: 27, name: "Devin Torres"}]}

Every component of Poison -- the encoder, decoder, and parser -- are all usable on their own without buying into other functionality. For example, if you were interested purely in the speed of parsing JSON without a decoding step, you could simply call Poison.Parser.parse.

If you use Poison 1.x, you have to set a module to as option in order to decode into a struct. e.g. as: Person instead of as: %Person{}. The change was introduced in 2.0.0.

Parser

iex> Poison.Parser.parse!(~s({"name": "Devin Torres", "age": 27}))
%{"name" => "Devin Torres", "age" => 27}
iex> Poison.Parser.parse!(~s({"name": "Devin Torres", "age": 27}), keys: :atoms!)
%{name: "Devin Torres", age: 27}

Note that keys: :atoms! reuses existing atoms, i.e. if :name was not allocated before the call, you will encounter an argument error message.

You can use the keys: :atoms variant to make sure all atoms are created as needed. However, unless you absolutely know what you're doing, do not do it. Atoms are not garbage-collected, see Erlang Efficiency Guide for more info:

Atoms are not garbage-collected. Once an atom is created, it will never be removed. The emulator will terminate if the limit for the number of atoms (1048576 by default) is reached.

Encoder

iex> IO.puts Poison.Encoder.encode([1, 2, 3], [])
"[1,2,3]"

Anything implementing the Encoder protocol is expected to return an IO list to be embedded within any other Encoder's implementation and passable to any IO subsystem without conversion.

defimpl Poison.Encoder, for: Person do
  def encode(%{name: name, age: age}, options) do
    Poison.Encoder.BitString.encode("#{name} (#{age})", options)
  end
end

For maximum performance, make sure you @derive [Poison.Encoder] for any struct you plan on encoding.

Encoding only some attributes

When deriving structs for encoding, it is possible to select or exclude specific attributes. This is achieved by deriving Poison.Encoder with the :only or :except options set:

defmodule PersonOnlyName do
  @derive {Poison.Encoder, only: [:name]}
  defstruct [:name, :age]
end

defmodule PersonWithoutName do
  @derive {Poison.Encoder, except: [:name]}
  defstruct [:name, :age]
end

In case both :only and :except keys are defined, the :except option is ignored.

Key Validation

According to the JSON spec keys in a JSON object should be unique. This is enforced and resolved in different ways in other libraries. In the Ruby JSON library for example, the output generated from encoding a hash with a duplicate key (say one is a string, the other an atom) will include both keys. When parsing JSON of this type, Chromium will override all previous values with the final one.

Like Ruby, Poison will also generate JSON with duplicate keys. If you'd like to ensure that your generated JSON doesn't have this issue, you can pass the strict_keys: true option when encoding. This will force the encoding to fail.

Note that validating keys can cause a small performance hit.

iex> Poison.encode!(%{:foo => "foo1", "foo" => "foo2"}, strict_keys: true)
** (Poison.EncodeError) duplicate key found: "foo"

Benchmarking

$ mix deps.get
$ MIX_ENV=bench mix compile
$ MIX_ENV=bench mix bench

License

Poison is released under CC0-1.0 (see LICENSE).

poison's People

Contributors

bennyhallett avatar optikfluffel avatar fishcakez avatar nettofarah avatar rschmukler avatar binaryseed avatar ch4s3 avatar niku avatar jisaacstone avatar waldyrious avatar jtmoulia avatar ono avatar sunaku avatar stevedomin avatar mitchellhenke avatar msch avatar frost avatar aesthetikx avatar cmpitg avatar asaaki avatar whatyouhide avatar

Watchers

Sebastian A. Espindola avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.