Rails应用程序:我需要从循环内的params构建一个json对象

时间:2017-01-14 10:15:49

标签: ruby-on-rails json loops

我需要使用params在循环内构建一个json对象。

我的参数看起来像这样......

params[:answers]
returns => {"1"=>"answer1", "2"=>"answer2"}

此json对象中的键是调查问题的ID。

所以我计划循环键来构建像这样的json对象......

def build_answersheet_json(params[:answers], params[:survey_id])
  params[:answers].keys.each do |question_id|
    current_question = question_id
    current_answer = params[:answers][question_id]
  end
end

因为我正在使用" t.json"在我的迁移中将json保存到postgres,我想使用提取的question_id并回答构建一个看起来像这样的json对象......

{
  survey_id: '1',
  answers: {
    question: [{
      question_id: 1,
      answer: 'answer1'
    }, {
      question_id: 2,
      answer: 'answer2'
      }]
  }
}

我一直试图使用看起来像这样的方法来做到这一点......

build_answersheet_json(params[:answers], params[:survey_id])

我已经尝试过JSON.parse(),我试图在逻辑上完成它,但我似乎无法解决这个问题。

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

也许你可以尝试这样的事情:

/* fake params (to test) */
params = {
    survey_id: '1',
    answers: {
        "1"=>"answer1", 
        "2"=>"answer2", 
        "3"=>"answer3", 
        "4"=>"answer4"
    }
}

def build_answersheet_json(answers, survey_id)
  {
    survey_id: survey_id,
    answers: answers.map { |k,v| { question_id: k.to_i, answer: v } }
  }
end


survey = build_answersheet_json(params[:answers], params[:survey_id])

puts survey.class 
#Hash

puts survey.to_json
# formated JSON string:
# {
#   "survey_id":"1",
#   "answers":[
#       {"question_id":1,"answer":"answer1"},
#       {"question_id":2,"answer":"answer2"},
#       {"question_id":3,"answer":"answer3"},
#       {"question_id":4,"answer":"answer4"}
#   ]
# }

为了保存到t.json postgress列类型,只需传递哈希survey对象,就像那样:

YourModel.create(survey: survey)

来源:http://edgeguides.rubyonrails.org/active_record_postgresql.html

答案 1 :(得分:1)

尝试

{
  survey: ¯\_༼◉ل͟◉༽_/¯,
}

答案 2 :(得分:0)

如果json具有这样的结构,则可能无法解析Json:

survey = {
}

Json可能不包含=和作业

在您遇到意外行为的代码行附近检查puts varname.inspect附近的实变量值。