tags:

views:

468

answers:

3

I have a list of tuples:

X = [{"alpha","beta"},{"gamma","theta"}].

I want to print X as a flat string using, io_lib:format("~s", [X]) in the following format:

[{"x":"alpha", "y":"beta"}, {"x":"gamma", "y":"theta"}]

How do I achieve this? I started using Map to do transform the list. But I was not able to print it as a string...(gave an unbound variable error on X).

+1  A: 

Furiously looks like JSON serializing ! You should give a look into rfc4627.erl as it does nearly exactly what you want.

cstar
A: 

If you want obscure thing, you can get obscure way:

6> io:format("~s~n",[lists:flatten([["{\"x\":\"",element(1, hd(X)),"\"},{\"y\":\"",element(2,hd(X))|"\"}"]|[[",{\"x\":\"",A,"\"},{\"y\":\"",B|"\"}"] || {A,B}<-tl(X)]])]).
{"x":"alpha"},{"y":"beta"},{"x":"gamma"},{"y":"theta"}
ok

You should not need it.

Hynek -Pichi- Vychodil
A: 

Try this:

tuplelist_to_string(L) ->
    tuplelist_to_string(L,[]).

tuplelist_to_string([],Acc) ->
    lists:flatten(["[",
        string:join(lists:reverse(Acc),","),
        "]"]);
tuplelist_to_string([{X,Y}|Rest],Acc) ->
    S = ["{\"x\":\"",X,"\", \"y\":\"",Y,"\"}"],
    tuplelist_to_string(Rest,[S|Acc]).

Then:

1> X = [{"alpha","beta"},{"gamma","theta"}].
[{"alpha","beta"},{"gamma","theta"}]
2> io:format("~s~n",[test:tuplelist_to_string(X)]).
[{"x":"alpha", "y":"beta"},{"x":"gamma", "y":"theta"}]
ok
Rob Charlton