【问题标题】:JSON & Rails: How to remove array brackets inside keypath of JSON resultsJSON & Rails:如何删除 JSON 结果的 keypath 中的数组括号
【发布时间】:2012-04-26 22:34:40
【问题描述】:

我有一个 JSON 格式问题——本质上我只是想删除从 Rails 控制器返回的 keypath 内的对象周围的数组 [ ]:

# channels controller
  def index
    @channels = Channel.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => { :channels => @channels } }
    end
  end

# channels.rb
  def as_json(options={})
    { self.id => self.attributes }
  end

# returns this JSON:
{"channels":[{"78":{"id":78,"name":"Zombie Bass","created_at":"2012-03-21T04:04:36Z","updated_at":"2012-04-20T01:21:12Z","num_of_listeners":1}},{"82":{"id":82,"name":"The Beatles123","created_at":"2012-03-22T20:28:34Z","updated_at":"2012-04-17T04:34:07Z","num_of_listeners":1}},{"125":{"id":125,"name":"New!","created_at":"2012-04-19T04:05:47Z","updated_at":"2012-04-19T04:05:47Z","num_of_listeners":1}},{"132":{"id":132,"name":"Test!","created_at":"2012-04-26T21:00:30Z","updated_at":"2012-04-26T21:00:30Z","num_of_listeners":1}}]}

# I want this JSON (just remove the array around all the channels):
{"channels":{"78":{"id":78,"name":"Zombie Bass","created_at":"2012-03-21T04:04:36Z","updated_at":"2012-04-20T01:21:12Z","num_of_listeners":1}},{"82":{"id":82,"name":"The Beatles123","created_at":"2012-03-22T20:28:34Z","updated_at":"2012-04-17T04:34:07Z","num_of_listeners":1}},{"125":{"id":125,"name":"New!","created_at":"2012-04-19T04:05:47Z","updated_at":"2012-04-19T04:05:47Z","num_of_listeners":1}},{"132":{"id":132,"name":"Test!","created_at":"2012-04-26T21:00:30Z","updated_at":"2012-04-26T21:00:30Z","num_of_listeners":1}}}

【问题讨论】:

  • 那么它就不再是一个有效的 JSON 了。

标签: ruby-on-rails ruby-on-rails-3 json


【解决方案1】:

这是不可能的。您不能在 JSON(这只是 JavaScript)中拥有不是数组或数组类型结构的对象列表。

如果您编辑您的问题以告诉我们您为何尝试实现这一目标,我们或许可以提供更多帮助。

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2019-11-01
    • 2014-11-03
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 2023-01-16
    • 2021-08-11
    相关资源
    最近更新 更多