1

I could 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!

1 Answer 1

1

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.

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

23 Comments

Thanks Jacob, but I'm still confused, the jquery plugin seems to error if there is a " around the "name" or "value" is that a bug in my rails code or the jQuery plugin?
@AnApprentice If the datatype of a value is not a string, then there shouldn't be quotes around the value.
@AnApprentice Please format your code using the ` characters.
@AnApprentice To be honest, I think I sufficiently answered your original question - there really shouldn't be an ongoing dialog which modify your original requirements. We're not here to hold your hand, we're here to answer specific questions.
@AnApprentice: Way to give thanks through a downvote for all the time he took to entertain you. Sure, you could have undone your upvote and left it at that, but to further downvote just because you realized it was a completely different issue from what the answer was addressing is just stupid.
|

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.