【问题标题】:Trouble parsing json/string version of array in Angular controller在 Angular 控制器中解析数组的 json/string 版本时遇到问题
【发布时间】:2016-10-27 20:11:25
【问题描述】:

为了更清楚而编辑的问题!

我正在构建一个 angular-rails 应用程序,但在解析数组时遇到了问题。我的一个 ActiveRecord 模型有一个属性数组。 在我的 Rails 控制器中,在它到达我的 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"
        ],
}

然后在我的角度控制器中,数组属性看起来像:

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

当然我需要它看起来像:

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

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

【问题讨论】:

    标签: javascript ruby-on-rails angularjs json


    【解决方案1】:

    解析 JSON

    解析另一个应用程序接收到的或生成的 JSON 字符串 在您现有的应用程序中:

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

    生成 JSON

    创建一个用于通信或序列化的 JSON 字符串就像 很简单。

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

    或者另一种方式:

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

    Ruby docs

    【讨论】:

    • 迟来的感谢您昨天的意见。我已经在上面编辑了我的问题,以使事情更清楚并添加更多信息,但长话短说,我没有运气在我的角度内的 array/json/string/whatever-it-is 属性上使用 JSON.parse()控制器。正如您在我的问题中从我的代码 sn-ps 中看到的那样,该对象似乎可以在 rails 端渲染正确的 json。我认为 Ruby 和 JavaScript 的解析方式肯定不同。
    猜你喜欢
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多