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

how to add another value to the existing JSON object in ruby on rails and Javascript?

本文关键字:JSON 对象 另一个 添加 ruby on rails Javascript      更新时间:2023-09-26

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"}"等。我需要添加另一列与现有的记录':'。

为javascript对象添加键/值对:

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

您可以在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'
    };
}