1

How do I convert a list with Tuples & Atoms & Binary strings in a list into JSON? I see Erlang : Tuple List into JSON and I found https://github.com/rustyio/BERT-JS

I want an API I can call like

erlang_json:convert([{a, b, {{c, d}}, 1}, {"a", "b", {{cat, dog}}, 2}

where the atoms would be converted to strings or some other standard way to process on the Javascript side.

I have complicated Erlang lists I need to send to my webpage.

quantumpotato
  • 9,637
  • 14
  • 70
  • 146

3 Answers3

4

It's unclear what [{a, b, {{c, d}}, 1}, {"a", "b", {{cat, dog}}, 2}... would turn into as JSON, but you might take a look at jiffy or jsx. Both of them work on simple key/value structures. For instance:

> Term = #{a => b, c => 1, <<"x">> => <<"y">>}.
#{a => b,c => 1,<<"x">> => <<"y">>}

> jiffy:encode(Term).
<<"{\"x\":\"y\",\"c\":1,\"a\":\"b\"}">>

> jsx:encode(Term).
<<"{\"a\":\"b\",\"c\":1,\"x\":\"y\"}">>

If you can say what JSON you want your example input to turn into, I might be able to give you a better suggestion.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • To add to this answer see https://github.com/davisp/jiffy#data-format to see the valid erlang datatypes that can give proper json. –  Dec 06 '16 at 07:00
  • Thanks -- I was hoping for each atom to turn into a string, as I don't think there's a way in JSON to send characters that aren't in strings. Your example code looks right so I will accept this, I will check into jiffy & jsx thank you! – quantumpotato Dec 07 '16 at 02:49
  • But still, [JSON](http://www.json.org/) is made up of key/value pairs. If you turn the atoms to strings, you still end up with something like `{"a", "b", {{"c", "d"}}, 1}` in erlang. What key/value pairs would you want pulled out of there? – Ryan Stewart Dec 07 '16 at 04:03
  • @RyanStewart yes, I understand. I was hoping to not have to write a custom JSON encoder for tuples eg. something that would convert tuples to arrays recursively and let the client side sort it out. – quantumpotato Jan 09 '17 at 22:30
3

Just for you https://github.com/romanr321/t2j

You don't need to wrap it in a list though, it takes one tuple argument and returnes a json formated string.

>Tuple = {{key, value}, { key2, {key3, [value1, 2,3]}}}.
>t2j:t2jp(Tuple).
{"key":"value", "key2, {"key3":["value1", 2,3]}}
Roman Rabinovich
  • 868
  • 6
  • 13
0

The library jsone is pretty good. It can translate between maps or tuples: https://github.com/sile/jsone

I've used it extensively and it's lightning fast.

The only problem I've found is that a map that contains a list of maps throws an error. I hope this is fixed, but maybe I'm the only tart trying to do that.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dale Sparrow
  • 121
  • 7