5

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!" }
    ]
}

1 Answer 1

14

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick response. Some frameworks - such as AngularJS - only consumes JSON without its root.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.