活动模型串行器格式化JSON显示
我在我的Rails应用程序中使用Active模型序列化程序,我想重构显示:
每当我去http:// localhost:3000 / api / users / 1时,我都会看到:
{"data":{"id":"1","type":"users","attributes":{"username":"Iggy1"},"relationships":{"items":{"data":[{"id":"1","type":"items"},{"id":"7","type":"items"}]},"lists":{"data":[{"id":"1","type":"lists"},{"id":"8","type":"lists"},{"id":"14","type":"lists"},{"id":"15","type":"lists"},{"id":"17","type":"lists"}]}}}}
我怎样才能让它看起来像:
{
"data": {
"id": "1",
"type": "users",
"attributes": {
"username": "Iggy1"
},
"relationships": {
"items": {
"data": [{
"id": "1",
"type": "items"
}, {
"id": "7",
"type": "items"
}]
},
"lists": {
"data": [{
"id": "1",
"type": "lists"
}, {
"id": "8",
"type": "lists"
}, {
"id": "14",
"type": "lists"
}, {
"id": "15",
"type": "lists"
}, {
"id": "17",
"type": "lists"
}]
}
}
}
}
我花了很多时间浏览适配器,渲染,架构,但我找不到指南。 首先,是否有可能使它看起来像上面的第二个代码块? 其次,如果可能的话,我必须做些什么来改变显示?
API / users_controller.rb
def show
@user = User.find_by(id: params[:id])
@no_user_found = User.all #other alternative when user ID not found?
if @user.nil?
flash[:notice] = "No user found"
render json: @no_user_found, each_serializer: UserSerializer
else
render json: @user, each_serializer: UserSerializer
end
end
user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :username#, :email
has_many :items, through: :lists
has_many :lists
end
的routes.rb
Rails.application.routes.draw do
ActiveModelSerializers.config.adapter = :json_api
namespace :api, defaults: { format: :json } do
resources :users do
resources :lists
end
resources :lists, only: [] do
resources :items, only: [:create, :index, :show, :update]
end
resources :items, only: [:destroy]
end
end
我建议使用邮递员pretty_generate
来代替使用浏览器。
您可以使用以下代码使用缩进和换行显示它:
<pre><%= JSON.pretty_generate(your_json_here) %></pre>
在上面的代码中,请执行以下操作:
<%
require 'json'
hash = JSON[{"data":{"id":"1","type":"users","attributes":{"username":"Iggy1"},"relationships":{"items":{"data":[{"id":"1","type":"items"},{"id":"7","type":"items"}]},"lists":{"data":[{"id":"1","type":"lists"},{"id":"8","type":"lists"},{"id":"14","type":"lists"},{"id":"15","type":"lists"},{"id":"17","type":"lists"}]}}}}.to_json]
%>
<pre>
<%= JSON.pretty_generate(hash)%>
</pre>
你的问题是关于样式的JSON输出。 正如上面建议的@araratan,你可以使用它来使你阅读。 而且没有必要在机器上使用时尚。 如果你在ThGenerate preety json outpur中需要相同的外观
链接地址: http://www.djcxy.com/p/47159.html