Code Monkey home page Code Monkey logo

elixir-json's Introduction

Build Status Hex.pm Coverage Status Inline docs

This library provides a natively implemented JSON encoder and decoder for Elixir.

You can find the package in hex.pm and the documentation in hexdocs.pm.

All contributions are welcome!

Installing

Simply add {:json, "~> 1.4"} to your project's mix.exs and run mix deps.get.

Usage

Encoding an Elixir type

  @doc "
	JSON encode an Elixir list
  "	
  list = [key: "this will be a value"]
  is_list(list)
  # true
  list[:key]
  # "this will be a value"
  {status, result} = JSON.encode(list)
  # {:ok, "{\"key\":\"this will be a value\"}"}
  String.length(result)
  # 41

Decoding a list from a string that contains JSON

  @doc "
	JSON decode a string into an Elixir list
  "
  json_input = "{\"key\":\"this will be a value\"}"
  {status, list} = JSON.decode(json_input)
	{:ok, %{"key" => "this will be a value"}}
  list[:key]
  # nil
  list["key"]
  # "this will be a value"

At any time, you can turn on verbose logging for this library only. To do so, head to config file of your application and add below lines:

use Mix.Config

config :logger, level: :debug

config :json, log_level: :debug

Note that, changing only :logger level to :info, :warn or :error will silent :json too.

License

The Elixir JSON library is available under the BSD 3-Clause aka "BSD New" license

elixir-json's People

Contributors

awetzel avatar bradleyd avatar cblage avatar danturn avatar falood avatar hectorip avatar kalloc avatar lowks avatar lsimoneau avatar mjaric avatar narnach avatar parroty avatar patrickdet avatar pauldipietro avatar readmecritic avatar ryosan-470 avatar sobolevn avatar wkhere avatar zambal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

elixir-json's Issues

JSON and Docker

Hi,

I am trying to generate a Docker container for an application that uses JSON. The Dockefile is basic:

FROM bitwalker/alpine-elixir:1.3.4

EXPOSE 4000
ENV PORT=4000 \
    MIX_ENV=prod

COPY . .
RUN \
    mix do deps.get, deps.compile && \
    mix do compile, release --verbose --env=prod && \
    mkdir -p /opt/myapp/log && \
    cp rel/myapp/releases/0.1.0/myapp.tar.gz /opt/myapp/ && \
    cd /opt/myapp && \
    tar -xzf myapp.tar.gz && \
    rm myapp.tar.gz && \
    rm -rf /opt/app/* && \
    chmod -R 777 /opt/app && \
    chmod -R 777 /opt/myapp

WORKDIR /opt/myapp

CMD ./bin/myapp foreground

When building the container There is an error in the json Dependency. This does not occur when I get or compile in my Red Hat Studio. It generates and the application runs properly.

I have already tried mix deps.compile json, update and clean

could not compile dependency :json, "mix compile" failed. You can recompile this dependency with "mix deps.compile json", update it with "mix deps.update json" or clean it with "mix deps.clean json"                                                                                                                                                      

20:15:39.606 [error] Native loading of /opt/app/_build/prod/lib/json/ebin/Elixir.JSON.beam failed: {:EXIT,
 {:badarg,
  [{:hipe_bifs, :patch_call, [1077937026, 140607107223148, []], []},
   {:hipe_unified_loader, :patch_call_insn, 3,
    [file: 'hipe_unified_loader.erl', line: 520]},
   {:hipe_unified_loader, :patch_bif_call_list, 4,
    [file: 'hipe_unified_loader.erl', line: 505]},
   {:hipe_unified_loader, :patch_call, 5,
    [file: 'hipe_unified_loader.erl', line: 496]},
   {:hipe_unified_loader, :patch, 5,
    [file: 'hipe_unified_loader.erl', line: 471]},
   {:hipe_unified_loader, :load_common, 5,
    [file: 'hipe_unified_loader.erl', line: 240]},
   {:hipe_unified_loader, :load_native_code, 3,
    [file: 'hipe_unified_loader.erl', line: 111]},
   {:code_server, :try_load_module_2, 6,
    [file: 'code_server.erl', line: 1111]}]}}

Can you help me?

Thanks

Travis build is breaking

Travis is broken, I think due to the map function ?

** (SyntaxError) test/json_encode_test.exs:48: invalid token: %{a: 1, b: %{b1: 21}}) \

(elixir) lib/code.ex:301: Code.require_file/2

(elixir) lib/kernel/parallel_require.ex:50: anonymous fn/4 in Kernel.ParallelRequire.spawn_requires/5

Update Elixir dependency for Elixir 1.0.0

Elixir 1.0.0 has been released. Using the latest elixir-json 0.3.0 results in:

warning: the dependency json requires Elixir "~> 0.14" but you are running on v1.0.0

Struct Support,

The library doesn't seem to support struct objects out of the gate. They're caught by the Any handler and serialized as something along the lines of [Elixir.Any]

Do you have a recommended best practice or any suggestions on making struct encoding/decoding straight forward.

I'm pretty new to the language but my initial workaround is to just do the following along with a use JsonStruct in any structures I need to encode. I think this approach could also be used to decode to struct with some additional metaprogramming magic but I have no idea if it's the best solution or if there is already a more straight forward undocumented way to easily decode/encode structs.

defmodule JsonStruct do
  use Behaviour
  defmacro __using__(_opts) do
    quote do
      import unquote(__MODULE__)
      @derive [Enumerable, Access]
      defimpl JSON.Encoder, for: __MODULE__ do
        def encode(dict), do: JSON.Encoder.Helpers.dict_encode(dict)
        def typeof(_), do: :object
      end
    end
  end
end

Passing char lists to Regex is deprecated

Hi,

first of all, thanks for the JSON library. Really easy to use & helpful.
While decoding some JSON I noticed the following deprecation warning.

Passing char lists to Regex is deprecated, please use binaries instead
    (elixir) lib/regex.ex:368: Regex.return_for/1
    (elixir) lib/regex.ex:119: Regex.match?/2
    (json) lib/json/numeric.ex:110: JSON.Numeric.to_integer_from_hex/1
    (json) lib/json/decode.ex:151: JSON.Decode.consume_unicode_escape/1
    (json) lib/json/decode.ex:145: JSON.Decode.consume_string_contents/1
    (json) lib/json/decode.ex:98: JSON.Decode.consume_object_value/3
    (json) lib/json/decode.ex:66: JSON.Decode.consume_array_contents/2

Responsible code:

  def to_integer_from_hex(bitstring) when is_binary(bitstring) do
    case bitstring_to_list(bitstring) |> to_integer_from_hex do
      { result, rest } -> {result, iolist_to_binary(rest)}
      :error -> :error
    end
  end

  def to_integer_from_hex(iolist) when is_list(iolist) do
    if Regex.match?(%r{^[0-9a-fA-F]}, iolist) do
      to_integer_from_hex_recursive(iolist, 0)
    else
      :error
    end
  end

I guess instead of transforming the bitstring to list & call to_integer_from_hex, it should directly call the Regex. To avoid API breaks it might be possible to translate the list to binary in the other function.

Does this sound fine? If yes I could try it & open a PR.

Comparison with Poison

Hey, could you provide a comparison with Poison? It clearly has a lot more momentum, why might I use this library instead?

Thanks!

[META] Moving this project to an organization to give community control over it

I would like to hear opinions about this, especially from people who contributed to the project.

I'm currently strongly considering "donating" the project to the community and put it under an organization (current tentative name: https://github.com/open-elixir).

Any opinions on the subject would be appreciated, I would still be contributing to the project as much as possible and reviewing pull requests, but I feel that a JSON library should not "belong" to any given user.

Thoughts?

cc: @josevalim, @ericmj, @hectorip, @jamesarosen, @vandrada, @parroty, @falood, @herenowcoder, @lsimoneau, @herenowcoder, @kalloc, @mathieul, @pminten, @patrickdet, @pauldipietro, @lowks

Escaping issues with forward slash

encode!/1 seems to be generating some incorrect escaping when I pass it a string with a forward slash:

iex(1)> JSON.encode!(dir: "uploads/")
"{\"dir\":\"uploads\\/\"}"

In this case the string I'd expect is "{\"dir\":\"uploads/\"}", since the forward slash doesn't need escaping at all.

decoded data is getting sorted.

Sorting is getting auto-applied on the map?

js = ~s({"headers": {
    "vary": "accept-encoding",
    "Content-Type": "application/json",
    "Date": "Wed, 7 Jul 2021 19:45:48 GMT",
    "Set-Cookie": "TS01485ddd=32a32ffd7883b9f012ae5729baac810f3; Path=/",
    "Transfer-Encoding": "chunked"
 }})

 IO.inspect JSON.decode!(js)
Result:
    %{
  "headers" => %{
    "Content-Type" => "application/json",
    "Date" => "Wed, 7 Jul 2021  19:45:48 GMT",
    "Set-Cookie" => "TS01485ddd=TS01485ddd=32a32ffd7883b9f012ae5729baac810f3; Path=/",
    "Transfer-Encoding" => "chunked",
    "vary" => "accept-encoding"
  }
}

Argument error when trying to parse unicode in JSON

The parser seems to have issues with some unicode strings.

iex(8)> JSON.decode("{\"name\": \"Fahad Al-Esmail \\u00f8\"}") {:ok, %{"name" => "Fahad Al-Esmail ΓΈ"}} iex(9)> JSON.decode("{\"name\": \"Fahad Al-Esmail \\ud83c\"}") ** (ArgumentError) argument error lib/json/parser/bitstring/string.ex:85: JSON.Parser.Bitstring.String.parse_escaped_unicode_codepoint/3 lib/json/parser/bitstring/string.ex:65: JSON.Parser.Bitstring.String.parse_string_contents/2 lib/json/parser/bitstring/object.ex:50: JSON.Parser.Bitstring.Object.parse_object_value/3 lib/json/decoder.ex:30: JSON.Decoder.BitString.decode/1

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.