Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!" }
    ]
}
like image 344
user1322092 Avatar asked Sep 20 '14 23:09

user1322092


1 Answers

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 
like image 146
BroiSatse Avatar answered Sep 30 '22 21:09

BroiSatse