如何美化 ActiveAdmin 的 json 输出?

How can I prettify json output for ActiveAdmin?

我有一个带有 json 字段的模型,我想美化该字段的输出。我该怎么做?

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

当前字段如下所示:

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

我想要这样的东西:

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

我会选择这样的东西:

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

如果您可以选择将 source 作为 Ruby 散列而不是 JSON 字符串,则您可能不需要 JSON.parse 调用。

您可能希望将输出包装到 <pre> HTML 标记中——就像 Evan Ross 建议的那样——以提高可读性:

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