Jignesh Gohel
Jignesh Gohel

Reputation: 6552

rails 3 as_json overridden to output custom property names, pretty print json without escaped characters

Rails v 3.0.11, Ruby v 1.9.3

Following is my class which includes ActiveModel::Serializers::JSON and overrides as_json to output JSON having custom property names. It uses other classes like Cell, Rows and Column which in turn has its own as_json overridden and the ActiveModel::Serializers::JSON included in them.

class DataObject

include ActiveModel::Serializers::JSON

attr_accessor :rows, :columns, :options

def initialize(rows = [], cols = [], options = {})
  @rows = rows
  @columns = cols
  @options = options
end

def add_row(row)
  @rows << row
end

def add_column(column)
  @columns << column
end

def attributes
  { 'rows' => rows, 'cols' => columns, 'options' => options}
end

def as_json(json_options = {})
  json_hash = {cols: columns, rows: rows}
  json_hash[:p] = options unless options.empty?
  json_hash
end

def create_data
  data = DataObject.new

  data.add_column(Column.new('A', 'New A', 'string'))
  data.add_column(Column.new('B', 'B-label', 'number'))
  data.add_column(Column.new('C', 'Label-C', 'date'))

  row1 = Row.new
  row1.add_cell(Cell.new('first-a'))
  row1.add_cell(Cell.new('first-b', 'First Alphabet B'))
  row1.add_cell(Cell.new('first-c', 'First CCCCC'))
  data.add_row(row1)

  row2 = Row.new
  row2.add_cell(Cell.new('second-a'))
  row2.add_cell(Cell.new('second-b', 'Second Alphabet B'))
  row2.add_cell(Cell.new('second-c', 'Second CCCCC'))
  data.add_row(row2)

  p data.to_json

 end

end

When I test this class from rails console like this:

1.9.3dev :001 > dobject = DataObject.new
 => #<DataObject:0xb8fa970 @rows=[], @columns=[], @options={}> 
1.9.3dev :002 > dobject.create_data

I get the following output in following format:

  => "{\"cols\":[{\"id\":\"A\",\"label\":\"New A\",\"type\":\"string\"},{\"id\":\"B\",\"label\":\"B-label\",\"type\":\"number\"},{\"id\":\"C\",\"label\":\"Label-C\",\"type\":\"date\"}],\"rows\":[{\"c\":[{\"v\":\"first-a\"},{\"v\":\"first-b\",\"f\":\"First Alphabet B\"},{\"v\":\"first-c\",\"f\":\"First CCCCC\"}]},{\"c\":[{\"v\":\"second-a\"},{\"v\":\"second-b\",\"f\":\"Second Alphabet B\"},{\"v\":\"second-c\",\"f\":\"Second CCCCC\"}]}]}"

It shows the JSON with escaped quotes which makes it difficult to be readable.

Is there any way in which the output can be displayed in a readable manner i.e. a formatted JSON?

Also how can I override as_json so that I can leverage its original supported options like :only, :except and :methods and also output JSON properties with desired names?

Thanks ,

Jignesh

Upvotes: 0

Views: 673

Answers (1)

noomerikal
noomerikal

Reputation: 791

For readable json output, this should work:

puts JSON.pretty_generate(JSON.parse(dobject.create_data))

Upvotes: 3

Related Questions