javascript - 在 Angular Controller 中解析数组的 json/string 版本时出现问题

标签 javascript ruby-on-rails angularjs json

编辑问题以使其更加清晰!

我正在构建一个 Angular-rails 应用程序,但在解析数组时遇到问题。我的 ActiveRecord 模型之一有一个属性数组。 在我的 Rails Controller 中,在到达我的 Angular 应用程序之前,该数组如下所示:

def show
  @thing = Thing.find(params[:id])
# @thing.list => ["{\"content\"=>\"first index\"}", "{\"content\"=>\"second index\"}"]
  render json: @recipe
end

# resulting json for @thing:

{
  id: 1,

  title: "thing",

  list: [
          "first index",
          "second index"
        ],
}

然后,一旦进入我的 Angular Controller ,数组属性如下所示:

thing.list => ["{"content"=>"one"}", "{"content"=>"two"}"]

当然我需要它看起来像:

[{content: "one"}, {content:"two"}]

我已经在应用程序的 Rails 和 Angular 端尝试过 JSON.parse,但没有成功。

最佳答案

Parsing JSON

To parse a JSON string received by another application or generated within your existing application:

require 'json'

my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"

Generating JSON

Creating a JSON string for communication or serialization is just as simple.

require 'json'

my_hash = {:hello => "goodbye"}
puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"

Or an alternative way:

require 'json'
puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"

Ruby docs

关于javascript - 在 Angular Controller 中解析数组的 json/string 版本时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40293426/

相关文章:

javascript - 通过 Angular 从 UL 中删除 LI

javascript - 查询的 NodeLists 中的 "order"有多可靠

Javascript/jQuery if 语句不比较任何内容

javascript - echarts自定义动态颜色

javascript - Rails 在销毁后在 js 中渲染另一个 Controller 操作

jquery - Rails 的模态窗口插件

javascript - 从 Tapestry 中的 JavaScript 函数内部提交表单

ruby-on-rails - 从 windows-1251 到 UTF-8 Ruby on Rails

javascript - 具有不同运行时配置的多个 Restangular 服务

javascript - ui-bootstrap-tpls 和 ui-bootstrap