Ruby JSON.Pretty_Generate ... Is Pretty Unpretty

Read nested hash and generate separate hash of similar structure

This should solve your problem:

def loop_params(schema)
new_parent = Hash.new

schema["fields"].each do |field|
new_key = field["key"]

if !field["group"].nil? && field["object"].nil?
new_parent[new_key] = parse_config(field)
else
new_parent[new_key] = loop_params(field)
end
end

new_parent
end

There are a few issues in your code that might be causing errors. Using @ to declare a variable makes it an instance variable, which means its value will persist after the function completes. Since we can't see the rest of your program, I don't know if you need all or any of them, but I wrote my solution without them.

A few other things to note:

if fields["object"].nil? & !fields["group"].nil?

your use of & is actually the bitwise operator and, rather than the conditional and. Use && instead.

Also, if you use puts instead of print, puts will automatically append a "\n" for you, which is a nice convenience to keep in mind.

How to output sorted hash in ruby template

Hash is an unordered data structure. In some languages (ruby, for example) there's an ordered version of hash, but in most cases in most languages you shouldn't rely on any specific order in a hash.

If order is important to you, you should use an array. So, your hash

{a: 1, b: 2}

becomes this

[{a: 1}, {b: 2}]

I think, it doesn't force too many changes in your code.

Workaround to your situation

Try this:

data = {beanstalkId: ['server1'], ccc: 2, aaa: 3}

data2 = data.keys.sort.map {|k| [k, data[k]]}

puts Hash[data2]
#=> {:aaa=>3, :beanstalkId=>["server1"], :ccc=>2}

ActiveRecord: Produce multi-line human-friendly json

I'll go out on a limb and say "no, there is no such option".

AFAIK, the JSON encoding is actually handled by ActiveSupport rather than ActiveRecord. If you look at lib/active_support/json/encoding.rb for your ActiveSupport gem, you'll see a lot of monkey patching going on to add as_json and encode_json methods to some core classes; the as_json methods are just used to flatten things like Time, Regexp, etc. to simpler types such as String. The interesting monkey patches are the encode_json ones, those methods are doing the real work of producing JSON and there's nothing in them for controlling the final output format; the Hash version, for example, is just this:

# comments removed for clarity
def encode_json(encoder)
"{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
end

The encoder just handles things like Unicode and quote escaping. As you can see, the encode_json is just mashing it all together in one compact string with no options for enabling prettiness.

All the complex classes appear to boil down to Hash or Array during JSONification so you could, in theory, add your own monkey patches to Hash and Array to make them produce something pretty. However, you might have some trouble keeping track of how deep in the structure you are so producing this:

{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
"nested":{
"not":"so pretty now",
"is":"it"
}
}

Would be pretty straight forward but this:

{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
"nested": {
"not":"so pretty now",
"is":"it"
}
}

would be harder and, presumably, you'd want the latter and especially so with deeply nested JSON where eyeballing the structure is difficult. You might be able to hang a bit of state on the encoder that gets passed around but that would be getting a little ugly and brittle.

A more feasible option would be an output filter to parse and reformat the JSON before sending it off to the browser. You'd have to borrow or build the pretty printer but that shouldn't be that difficult. You should be able to conditionally attach said filter only for your development environment without too much ugliness as well.

If you're just looking to debug your JSON based interactions then maybe the JSONovich extension for Firefox would be less hassle. JSONovich has a few nice features (such as expanding and collapsing nested structures) that go beyond simple pretty printing too.


BTW, I reviewed Rails 3.0 and 3.1 for this, you can check Rails 2 if you're interested.

Is there a nice way to use url_for with ActiveResource?

ActiveResource wasn't meant to be used this way. It is implemented to be very close to ActiveRecord. Routes are per definition local. If you are referencing another site, you are not linking to this application anymore, thus the normal routes won't help you (much).

The default helpers work on naming conventions alone. The only thing url helpers will do with objects is call to_param to get the identifier for individual resources.

I don't know if there is a gem that can help you, but I fear you have to make your own helpers.

How to add JSON file export functionality in Rails 4.2

You can easily use to_json method, send_data with disposition header:

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
def users_json
data = User.all.to_json
send_data data, :type => 'application/json; header=present', :disposition => "attachment; filename=users.json"
end
end


Related Topics



Leave a reply



Submit