编辑问题以使其更加清晰!
我正在构建一个 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\"}"
关于javascript - 在 Angular Controller 中解析数组的 json/string 版本时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40293426/