从params hash制作json

时间:2014-06-27 05:19:34

标签: ruby json hash

我正在尝试调用API并将数据从我form中的view传递给controller,然后使用post方法调用API。

我在params得到的是:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"kLLaVRc6kcndkfB1nkntSTzGCg95CMCT1UvEncqwLgc=", 

"score_sheet"=>{

  "score_sheet_master"=>{

    "issue_date(1i)"=>"2014", "issue_date(2i)"=>"6", "issue_date(3i)"=>"27"}, 

  "print_date(1i)"=>"2014", "print_date(2i)"=>"6", "print_date(3i)"=>"27", "product_id"=>"2", "pull_id"=>"2", "press_run_id"=>"1", "total_section"=>"2", 

  "score_sheet_sections_attributes"=>{

    "0"=>{"section_name"=>"A", "total_pages"=>"2", "color_pages"=>"1", "_destroy"=>"false"}, 

    "1"=>{"section_name"=>"B", "total_pages"=>"1", "color_pages"=>"", "_destroy"=>"false"}},   

  "color_pages_rated"=>"1", "bw_pages_rated"=>"2", "foreman_id"=>"", "pic_id"=>""}, 

  "score_sheet_master"=>{

    "press_id"=>"1"}, 

  "commit"=>"Create Score sheet"}

我希望将此哈希转换为JSON APIs接受的{ "score_sheet": { "score_sheet_master": { "issue_date": "2014-06-25", "press_id": "1" }, "print_date": "2014-06-23", "product_id": 1, "pull_id": 2, "press_run_id": 1, "total_section": 2, "score_sheet_sections_attributes": [ { "section_name": "A", "total_pages": 3, "color_pages": "2,3", "id": 9 }, { "section_name": "B", "total_pages": 1, "color_pages": "1", "id": 10 }, { "section_name": "C", "total_pages": 2, "color_pages": "2" } ], "pic_id": 1, "foreman_id": 1 } } 。 I-E。

date conversion

JSON中的某些字段可能会丢失,或者可能比HASH更多,但我并不关心我将亲自处理它们,主要问题是将此params Hash转换为所需的JSON。 坚持我已经实现了score_sheet_sections_attributes正常工作的事情。但不知道如何将{{1}}数组格式转换为所需的格式

1 个答案:

答案 0 :(得分:0)

哦,我自己了:

sections = []
params["score_sheet"]["score_sheet_sections_attributes"].each {|k,v| sections << v}
params["score_sheet"]["score_sheet_sections_attributes"] = sections

给出了:

{"utf8"=>"✓", "authenticity_token"=>"kLLaVRc6kcndkfB1nkntSTzGCg95CMCT1UvEncqwLgc=", "score_sheet"=>{"score_sheet_master"=>{"issue_date(1i)"=>"2014", "issue_date(2i)"=>"6", "issue_date(3i)"=>"27"}, "print_date(1i)"=>"2014", "print_date(2i)"=>"6", "print_date(3i)"=>"27", "product_id"=>"2", "pull_id"=>"2", "press_run_id"=>"1", "total_section"=>"2", "score_sheet_sections_attributes"=>[{"section_name"=>"A", "total_pages"=>"2", "color_pages"=>"1", "_destroy"=>"false"}, {"section_name"=>"B", "total_pages"=>"1", "color_pages"=>"", "_destroy"=>"false"}], "color_pages_rated"=>"1", "bw_pages_rated"=>"2", "foreman_id"=>"", "pic_id"=>""}, "score_sheet_master"=>{"press_id"=>"1"}, "commit"=>"Create Score sheet"}

并且对于日期我实施了另一个逻辑并且全部完成。