简体   繁体   English

如何将数组转换为JSON对象

[英]How do I convert an array to a JSON object

I am new to ROR, I have some seed data stored in my database table and a YAML file. 我是ROR的新手,我的数据库表和YAML文件中存储了一些种子数据。 I have been loading the yaml file and converting it into a JSON which I parsed and displayed to the client. 我一直在加载yaml文件并将其转换为我解析并显示给客户端的JSON。

Something like this. 这样的事情。

controller.rb controller.rb

def template_library
    @template_library_all= YAML::load(File.open('./db/seeds/template_library.yml'))
end

In my view I did 我认为我做到了

reports.html.slim report.html.slim

javascript:
  var templateLibraryJSON = #{@template_library_all.to_json.html_safe};

So now I want to use the model to get the data from the database and parse it into JSON, instead of using a static file. 因此,现在我想使用该模型从数据库获取数据并将其解析为JSON,而不是使用静态文件。

What I have done so far. 到目前为止我所做的。

def query_library
@template_library_JSON = TemplateLibrary.all.map { |i| ['file_name:' , [i.file_name]]}
end

in my view 在我看来

javascript:
  var templateJSON = #{@template_library_JSON.to_json.html_safe};

this returns me a JSON which looks like a JSON array. 这会给我返回一个JSON,看起来像JSON数组。

[["file_name:", ["daily_data_count_report"]]]

Do I have to construct the JSON object ? 我是否必须构造JSON对象?

It looks like your #map call returns an array of arrays, not a hash. 看起来您的#map调用返回的是数组数组,而不是哈希。 Try this instead: 尝试以下方法:

@template_library_JSON = TemplateLibrary.all.map { |i| { :file_name => i.file_name } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM