0

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!

1 Answer 1

2

Simply do this:

metric_types = MetricType.all
hash = {:metrics => metrics_types}

then go

format.json {render :json => hash}

You may be interested in Rabl

Sign up to request clarification or add additional context in comments.

1 Comment

@sko Good stuff, maybe tick the tick box to let anyone else who viewed this question know that it worked.

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.