JSON - 计算Ruby中的项目数

时间:2017-06-28 10:44:31

标签: ruby-on-rails json ruby

我有一个Json对象如下:

jsonobject = {
"fruits": [
    {
        "name": "A",
        "uri": "a.com"
    },
    {
        "name": "B",
        "uri": "b.com"
    }
],
"trees": [
    {
        "name": "t1",
        "uri": "t1.com",
        "status": null
    },
    {
        "name": "t2",
        "uri": "t2.com",
        "status": null
    }
]
}

如何在Ruby中获取树木/水果的数量?

1 个答案:

答案 0 :(得分:4)

首先,进行小幅修正。你的jsonobject应该是一个字符串。将整个jsonobject用单引号括起来。

jsonobject = '{"fruits": [{"name": "A","uri": "a.com"},{"name": "B","uri": "b.com"}],"trees": [{"name": "t1","uri": "t1.com","status": null},{"name": "t2","uri": "t2.com","status": null}]}'

你可以在这里使用ruby的JSON库......

树木数量

JSON.parse(jsonobject)["trees"].size

水果数量

JSON.parse(jsonobject)["fruits"].size

<强>更新 如何将jsonobject设为字符串

jsonobject =%q({&#34; fruits&#34;:[{&#34; name&#34;:&#34; A&#34;,&#34; uri&#34;:&#34 ; a.com&#34;},{&#34;姓名&#34;:&#34; B&#34;,&#34; uri&#34;:&#34; b.com&#34;}], &#34;树&#34;:[{&#34;名称&#34;:&#34; t1&#34;,&#34; uri&#34;:&#34; t1.com&#34;,& #34; status&#34;:null},{&#34; name&#34;:&#34; t2&#34;,&#34; uri&#34;:&#34; t2.com&#34;, &#34; status&#34;:null}]})