I co开发者_StackOverflowuld use your helping creating a valid JSON object in Rails.
Here is an example of a valid JSON object that I'm using in the jQuery plugin: https://drew.tenderapp.com/kb/autosuggest-jquery-plugin
var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}]};
Within Rails I'm creating my object as follows:
@projects = Projects.all
@projectlist = Array.new
@projectlist << {
:items => @projects.map { |project|
{
:name => space.name,
:value => space.id
}
}
}
But this ends up outputting like so which ERRORs by the plugin:
[{"items":[{"value":74,"name":"XXXXXX"},{"value":71,"name":"XXXXXX"},{"value":70,"name":"XXXXXX"}]}]
Looks like there is a [] around the initial {} any idea why that's happening and how to build a valid JSON object?
Thanks!
Simply assign @projectlist
to a Hash
, like so:
EDIT After looking at the plugin's API, I've come to the conclusion that you need to convert your value
s to strings first:
@projects = Projects.all
@projectlist = {
:items => @projects.map { |project|
{
:name => space.name,
:value => space.id.to_s
}
}
}
Since you're initializing @projectlist
to an Array
and pushing the Hash
onto it, you're getting those wrapping []
characters.
精彩评论