user1903663 user1903663 - 6 months ago 16
Ruby Question

how can I convert a twilio return into json and print on html page?

I am using sinatra and ruby with twilio-ruby gem. I get a list of numbers with the following code:

@numbers = @subaccount.available_phone_numbers.get('US').local.list({:area_code => '858'})
puts "Available numbers:"
num = @numbers.each {|num| puts num.phone_number}
{number:num}.to_json


In the terminal window it appears a list, like so:

Available numbers:
+18589240128
+18588779651
+18582231372
+18589141380
+18588779811
+18589141390
+18582231256


etc. cut for brevity.

But on the website page it appears as:

{"number["#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#"]}


So my question is: how can I convert the return, from Twilio, into usable json so that I can access it through jquery getJSON and then print it on my HTML page?

Many thanks as always ....

Answer

Twilio developer evangelist here.

I'm not sure exactly what's going on here, as I can't get the same result in testing. However, I think it has something to do with the way you are using puts and each.

You appear to be trying to get the num array to be an array of phone numbers, however each just returns the original array, so you remain with an array of objects.

Try the following:

@numbers = @subaccount.available_phone_numbers.get('US').local.list({:area_code => '858'})
puts "Available numbers:"
num = @numbers.map {|num| puts num.phone_number; num.phone_number } 
{number:num}.to_json

Map will return an array with the result of the block in place of the original array, so this will print out the phone number with puts and then return the phone number itself. Then your num array is just an array of those phone numbers and should read out correctly in the json.

Let me know if this helps.

Comments