1

I have the following:

Body = "{\"auth\": {\"tName\": \"str1\", \"passwordCredentials\": {\"username\": \"u\", \"password\": \"p\"}}}"

The data I use can't be hardcoded; I need to build Body based on the variables TName = "str1", UName="u", and Password="p":

I tried:

Body = "{\"auth\": {\"tName\": TName, \"passwordCredentials\": {\"username\": UName, \"password\": Password}}}"

But with this approach Body was not constructed properly. How can I use variables to build it?

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

2 Answers2

3

Erlang doesn't have any kind of string interpolation. You can do

Body = "{\"auth\": {\"tName\": " ++ TName ++ ", \"passwordCredentials\": {\"username\": " ++ UName ++ ", \"password\": " ++ Password ++ "}}}"

or

Body = lists:append(["{\"auth\": {\"tName\": ", TName, ", \"passwordCredentials\": {\"username\": ", UName, ", \"password\": ", Password, "}}}"])

(Change in the obvious way if you need to add quotes around TName and the rest.)

Much better, instead of constructing a string like this (do you really want to deal with all the \", counting closing braces, etc.?), write a simple function which would take an Erlang term like [{auth, [{tName, TName}, {passwordCredentials, [{userName, UName}, {password, Password}]]] and builds the JSON string from it (I recommend using binaries instead of strings for TName etc., since Erlang strings are just lists of numbers, and you may want to have lists of numbers in your term which aren't strings). Or use an existing JSON library (see What is the most mature JSON library for Erlang for some suggestions), especially if you don't just need to build JSON but parse it as well.

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

For making JSON I would definitely use some JSON library:

body(TName, UName, Password) ->
    jiffy:encode({
      [{<<"auth">>, {
            [{<<"tname">>, iolist_to_binary(TName)},
             {<<"passwordCredentials">>, {
                  [{<<"username">>, iolist_to_binary(UName)},
                   {<<"password">>, iolist_to_binary(Password)}]
                 }}]
           }}]
     }).
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73