Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prettify json output for ActiveAdmin?

I have a model with json field and I want to prettify the output for this field. How can I do it?

show do
  attributes_table do
    row :source_json do |model|
      model.source_json
    end
  end
end

Current field looks like this:

  {"date"=>"2018-12-17", "value"=>"sample"}

I want something like this:

  {
     "date"=>"2018-12-17",
     "value"=>"sample"
  }
like image 216
Vlad Hilko Avatar asked Oct 29 '25 09:10

Vlad Hilko


1 Answers

I would go with something like this:

show do
  attributes_table do
    row :source_json do |model|
      JSON.pretty_generate(JSON.parse(model.source_json))
    end
  end
end

You might not need the JSON.parse call if you have an option to get source as a Ruby hash instead of a JSON string.

You might want to wrap the output into a <pre> HTML tag – like Evan Ross suggested – to improve readability:

show do
  attributes_table do
    row :source_json do |model|
      tag.pre JSON.pretty_generate(JSON.parse(model.source_json))
    end
  end
end
like image 100
spickermann Avatar answered Oct 31 '25 00:10

spickermann