Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am new to JSON and Ruby on Rails (ruby 1.9.3, rails 3.2.13) and I am trying to add an array name/identifier to a JSON object that contains an already defined array.

My ruby on rails code in a controller is:

metricTypes = MetricType.all
respond_to do |format|
    format.json {render :json => metricTypes}
end

What gets spit out is:

[
    {
        "id":1,
        "name":"foo"
    },
    {
        "id":2,
        "name":"bar"
    }
]

but what I would like to get is:

{
    metrics: [
        {
             "id":1,
             "name":"foo"
        },
        {
              "id":2,
              "name":"bar"
        }
    ]
}

How can I modify the JSON object to include the array name/identifier? I may need to include other arrays other than "metrics" in the same json object in the future, which is why I am trying to do this. Thanks!

share|improve this question

1 Answer 1

Simply do this:

metricTypes = MetricType.all
hash = {:metrics => metricsTypes}

then go

format.json {render :json => hash}

You may be interested in Rabl

share|improve this answer
    
This worked, Thanks!! –  sko Nov 13 '13 at 19:55
    
@sko Good stuff, maybe tick the tick box to let anyone else who viewed this question know that it worked. –  Niall Nov 13 '13 at 20:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.