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!" }
    ]
}
                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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With