如何在ruby on rails和Javascript中为现有的JSON对象添加另一个值?

时间:2013-01-15 11:42:40

标签: javascript jquery ruby-on-rails ruby ruby-on-rails-3

在我喜欢的model中,

  def question_hash_string
    @question_hash_string || '{}'
  end

  def question_hash
    ActiveSupport::JSON.decode question_hash_string
  end

Javascript

var question_hash_element = document.getElementById('enr_rds_batch_update_question_hash_string');
var question_hash = JSON.parse(question_hash_element.value);

question_hash[batch_question_id] = (batch_answer_id || batch_rdsap_answer || batch_answer_checkbox);
question_hash_element.value = JSON.stringify(question_hash);

它会提供类似"{"16":"3","28":false}"

的值

我想用以下答案添加另一个值,

question_hash[batch_question_id] = ((batch_answer_id || batch_rdsap_answer || batch_answer_checkbox) && (build_id));

"{"16":"3","28":false:"2", "3":"55":"54"}"等等。我需要使用':'添加另一个包含现有记录的列。

2 个答案:

答案 0 :(得分:2)

将键/值对添加到javascript对象:

var question_hash = { question_id:2, answer_id:3 };
question_hash.build_id = 6;

答案 1 :(得分:0)

您可以在JavaScript代码中添加新元素。

function doSomething(value) {
   var jsonValues = getParameters();

   jsonValues.value3 = value; //Here you add a new value in your json
}

//Example of function to generate json
function getParameters() {

    return {
        value: 'a',
        value1: 'b',
        value2: 'c'
    };
}