0

I have several variables, not literals, that I want include in a json string. This doesn't work:

a1 = get_email
a2 = get_user_name

json1 = '{"email": a1, "username": a2}'

because the variables aren't evaluated.

And doing this the other way around will make json invalid because single quotation marks aren't allowed in json:

a1 = get_email
a2 = get_user_name

json1 = "{'email': a1, 'username': a2}"

How can I create a json with those variables?

Omanokoto
  • 51
  • 3

2 Answers2

6

Easiest way to do this is to first use a hash:

a1 = get_email
a2 = get_user_name

json1 = {'email'=> a1, 'username'=> a2}.to_json
adrienbourgeois
  • 423
  • 1
  • 3
  • 8
2

Using to_json as in adrienbourgeois's answer is the correct way after all, but going along the lines of what you suggested, you should have done:

json1 = "{\"email\": #{a1}, \"username\": #{a2}}"

provided that a1.to_s and a2.to_s give the JSON format of whatever object you have in it (which you have not made clear in your question).

sawa
  • 165,429
  • 45
  • 277
  • 381