Skip to main content
fix title typo
Link
tomahh
  • 13.7k
  • 3
  • 53
  • 72

How do I convert an array to ana JSON object

Source Link
yesh
  • 2.1k
  • 5
  • 30
  • 52

How do I convert an array to an JSON object

I am new to ROR, I have some seed data stored in my database table and a YAML file. I have been loading the yaml file and converting it into a JSON which I parsed and displayed to the client.

Something like this.

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

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.

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.

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

Do I have to construct the JSON object ?