0

可能重复:
如何使用 Ruby on Rails 解析 JSON?

我是一名 PHP 程序员,最近我切换到 Rails。

我在将 JSON 输出转换为数组时遇到问题。

在 PHP 中我经常使用该json_decode函数。它可以轻松地将 JSON 字符串转换为 PHP 数组,但在 Rails 中我找不到这种类型的函数。

这是我的 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"}}]}

我正在使用这段代码:

@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}"

但是,它不起作用。我怎样才能restaurantname进去@test

4

1 回答 1

0

给定一个 json(或 rails (hash) 中的等价物) foo = {"posts": { ....

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

引用第一个元素(帖子)索引数组元素(或循环遍历它)并引用您想要的元素。

从 Rails 的角度来看,您的 json 的结构是: hash in array in hash (或 {"foo":[{"bar": 1}]} )

于 2013-01-26T12:19:37.150 回答