[erlang-questions] Access JSON in Erlang like you do in JavaScript

Richard O'Keefe ok@REDACTED
Wed Oct 20 07:22:40 CEST 2010

On 20/10/2010, at 10:57 AM, Ryan Zezeski wrote:

> I feel like a lot of people tend to feel pain when working with JSON in
> Erlang.  Especially when trying to access nested values.  I wrote a blog
> post about a way you can access JSON in Erlang using the same syntax you
> would in JavaScript.
> http://www.progski.net/blog/2010/destructuring_json_in_erlang_made_easy.html

In Javascript you would access a single item using something like


where i1, i2, i3 are non-negative integer array indices or
string hash keys.  Suppose you have an implementation of EEP 18
(http://www.erlang.org/eeps/eep-0018.html).  Then

	at(JSON = [H|_], Index) when is_tuple(H) ->
	    if is_atom(Index) ; is_binary(Index) ->
		{value,{Index,Item}} = lists:keysearch(Index, 1, JSON),
	at(JSON, Index) when is_list(JSON), is_integer(Index) ->
	    lists:nth(Index + 1, JSON).

	at(JSON, I1, I2)         -> at(at(JSON, I1), I2).
	at(JSON, I1, I2, I3)     -> at(at(JSON, I1), I2, I3).
	at(JSON, I1, I2, I3, I4) -> at(at(JSON, I1), I2, I3, I4).

	at_path(JSON, []) -> JSON;
	at_path(JSON, [X|Xs]) -> at_path(at(JSON, X), Xs).

and now thingy[i1][i2][i3] becomes
	at(Thingy, I1, I2, I3)
or	at_path(Thingy, [I1,I2,I3]).

One example in the link would be

	at(Obj, <<"post">>, <<"title">>)

Another would be just

	at(Obj2, <<"person">>, <<"friends">>, 1)

Adjusting this to the data structure used by mochijson2 would be simple too.
It hardly seems worth adding special syntax and transformations to Erlang
for something this simple.

So what am I missing?


More information about the erlang-questions mailing list