user1322092
user1322092

Reputation: 4280

How to count number of JSON objects in Ruby/Rails

How can one in Ruby "generically" count the number of objects for JSONs in the below formats (rooted, unrooted)? By generically, I mean the elements may be different ("title" for instance by be called something else).

without root:

{
    [
      { "title": "Post 1", "body": "Hello!" },
      { "title": "Post 2", "body": "Goodbye!" }
    ]
}

root wrapped:

{
  "posts":
    [
      { "title": "Post 1", "body": "Hello!" },
      { "title": "Post 2", "body": "Goodbye!" }
    ]
}

Upvotes: 5

Views: 9231

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

Firstly, without root code is not a valid json format. It would be without surrounding curly brackets, so I'm gona assume that's how it should be.

In first case:

json = '[
  { "title": "Post 1", "body": "Hello!" },
  { "title": "Post 2", "body": "Goodbye!" }
]'

require 'json'
ary = JSON.parse(json)
puts ary.count

The other case is not much different:

json = '{
  "posts":
    [
      { "title": "Post 1", "body": "Hello!" },
      { "title": "Post 2", "body": "Goodbye!" }
    ]
}')

require 'json'
hash = JSON.parse(json)
puts hash['posts'].count 

Upvotes: 14

Related Questions