Omanokoto
Omanokoto

Reputation: 51

How to properly create JSON with variables?

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?

Upvotes: 0

Views: 1582

Answers (2)

sawa
sawa

Reputation: 168081

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).

Upvotes: 2

adrienbourgeois
adrienbourgeois

Reputation: 432

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

Upvotes: 6

Related Questions