Jump to content

The ultimate community for Ruby on Rails developers.


Photo

hash to json

hash json controller

  • Please log in to reply
4 replies to this topic

#1 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 13 July 2014 - 10:17 PM

The following renders as json

 15   def bucket_items
 16     @bucket_items = ['key', 'not really a value']
 17     respond_to do |format|
 18       format.json { render json: @bucket_items }
 19     end
 20   end

But this does not appear to

 15   def bucket_items
 16     @bucket_items = {'key' => 'value'}
 17     respond_to do |format|
 18       format.json { render json: @bucket_items }
 19     end
 20   end

How do I render a hash as json? What I really want to do is have an array of hashes that gets turned into json in the controller and then looped through in coffeescript.



#2 Ohm

Ohm

    Driver

  • Moderators
  • 368 posts
  • LocationCopenhagen

Posted 13 July 2014 - 10:22 PM

Just call to_json manually on the hash.

def bucket_items
  @bucket_items = { 'key' => 'value' }
  respond_to do |format|
    format.json { render json: @bucket_items.to_json }
  end
end

Blog: http://ohm.sh | Twitter: @madsohm

#3 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 13 July 2014 - 10:34 PM

Still does the same thing. I pushed the response to the console like so:

  7 $.ajax(url: "/mock/bucket_items").done (json) ->
  8     $('body').append json
  9     console.log json

And the console output is this:

Object { key="value"}

A javascript object. I could definitely loop through attributes of an object like this but I don't think this is the standard way of getting json, parsing it, and then populating a page using that content.



#4 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 13 July 2014 - 10:34 PM

Or is it?



#5 NerdcoreSteve

NerdcoreSteve

    Signalman

  • Members
  • 25 posts

Posted 13 July 2014 - 11:08 PM   Best Answer

Actually I think that's a pretty good way to go. I think I'll just mess around with the object.







Also tagged with one or more of these keywords: hash, json, controller

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users