【问题标题】:JSON - Count number of items in RubyJSON - 计算 Ruby 中的项目数
【发布时间】:2017-12-01 16:31:01
【问题描述】:

我有一个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 中获取树木/水果的数量?

【问题讨论】:

  • 你能说清楚这段代码的上下文吗?
  • 我得到这个 json 对象作为 HTTP GET 请求的输出。现在我只想计算“水果”和“树木”中的项目数量。我使用了这些名称,而不是我实际获得的信息。只是不透露信息。你现在可以帮忙吗?
  • json = JSON.parse(jsonobject)["trees"].size?

标签: ruby-on-rails json ruby


【解决方案1】:

首先,进行一个小的修正。你的 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({"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​​ 中首先成为字符串?
  • 成功了。万分感谢。一个小小的疑问。如果我有 jsonobject 作为其他程序的输出,并且我想计算元素,我怎么能做到这一点而不将它写在单独的程序中。我可以写 jsonobject = %qjsonobject 吗?
  • 是否可以共享您实际收到 jsonobject 的代码。您在另一个程序中使用什么语言。如果您可以发布与此相关的新问题会更好。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多