开发者

Rails Creating a Valid JSON object

开发者 https://www.devze.com 2023-02-02 17:48 出处:网络
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/autos

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 values 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号