Using records for json objects

Hi.

I’d like to use records as json object, because the handling of records is quite nice with the available macros for records.
For json I use the library ljson (GitHub - lfex/ljson: An LFE library which provides a unified JSON experience). However, it seems it can only deal with tuples. Now since records are tuples I thought this might actually work. But it doesn’t.

Creating a record:

lfe> (defrecord foo (a) (b) (c))
set-foo-c
lfe> (set f (make-foo a #"a" b #"b" c #"c"))
#(foo #"a" #"b" #"c")

As it seems the tuples do not have the tuple structure of key:value useable for ljson for encoding because json objects require at least two entries per tuple to represent key:value.

Is there some way to convert a record into a tuple form that would work for ljson?

Manfred

2 Likes

Not directly. LFE records exactly mirror Erlang records in that they only contain the values and not the key names. You could write a special defjson which gives the right format with usable interfaces.

Maybe you could use records and just have double the fields, for key foo have foo-key and foo-value fields in the records but it would give a flat tuple #(foo <key-name> <key-value> <key-name> <key-value> ...) tuple. If of course this is the structure you want.

What does the json tuple look like?

3 Likes

Yep, thanks. ljson needs tuples of pairs. So the flat hierarchy wouldn’t work.
But that’s OK. I’ll can create factory function that create the tuples I need. Once they are created they actually don’t need to change.

1 Like

Have a look to my erlang library ?

3 Likes

Thanks, I’ll check it out.
I believe ljson works with jsx under the hood. But effectively it doesn’t matter and one probably wouldn’t need the additional abstraction.
I’ve planed to make a facade for the json access anyhow which would allow me to easily switch json providers.

2 Likes

Wiki will give you many informations and examples. Jason (nothing to do with elixir lib using same name) was created mainly for records. Enjoy.

2 Likes