0

Possible Duplicate:
How do I parse JSON with Ruby on Rails?

I am a PHP programmer and recently I switched to Rails.

I am having problems converting JSON output to an array.

In PHP I often used the json_decode function. It easily converts JSON strings to PHP arrays, but in Rails I couldn't find such type of function.

This is my JSON:

{"posts":[{"post":{"id":"1","createdOn":"2012-11-07 07:09:03","updatedOn":"2013-01-14 02:39:55","restaurantname":"Sapori","contractno":"307","listingtype":"Full","address":"Valley Road,","location":"Birkirkara","phone":"21494679","website":"N\/A","cuisine":",32,33,","onetimeofferexlunch":",50:monday,50:tuesday,50:wednesday,50:thursday,50:friday,50:saturday,50:sunday,","onetimeofferexdinner":",50:monday,50:tuesday,50:wednesday,50:thursday,50:friday,50:saturday,50:sunday,","ongoingdiscountlunch":"","ongoingdiscountdinner":"","unlimitedofferinfo":"Unlimited Discount 15% on the food bill for the whole table.","reservationrequired":"No","desertincluded":"Yes","membershipspertable":"Unlimited","openingclosing":"Open 09:00-23:00 everyday.","amenities":",,","description":"","fbcode":"","mark_new":"No","ownerfname":"David Testing for check tv webservice","ownermname":"","ownerlname":"Xuereb","designation":"Owner","ownerphone":"79428796","owneremail":"saporicafe@melita.com","ownerpassword":"sSj1eQnngA","uploadmenu":"","serialno":"0","status":"1","latitude":"35.896368","longitude":"14.463627","rate_review_code":"1RtKdrqFHe","imgurl_0":"http:\/\/v3.gusto.com.mt\/upload\/image\/0\/image73_1322041350.jpg","Rating Message":"Rated 8.2 by 78 Members","Average":"8.2","cuisine_1":"Pasta","cuisine_2":"Pizzeria"}}]}

I am using this code:

@result= open("http://v3.gusto.com.mt/webservice/getrestaurnatdetails.php?id=1&format=json").read    
@result = ActiveSupport::JSON.decode(@result)
@result["posts"].each{|p| @test=puts p["restaurantname"] }
puts"@@@@@@@@@@@@@@@@@@@@@@@@@@ RESTAURANT #{@test.inspect}"

But, it's not working. How can I get restaurantname in @test?

Community
  • 1
  • 1
tv.ashvin
  • 705
  • 2
  • 7
  • 13

1 Answers1

0

given a json (or the equivalent in rails (hash) foo = {"posts": { ....

foo["posts"].each{|p| puts p["restaurantname"] }

reference the first element (posts) the index an array element (or loop through it) and reference the element you want.

the structure of your json from a rails point of view is: hash in array in hash (or {"foo":[{"bar": 1}]} )

scones
  • 3,317
  • 23
  • 34