A JSON file contains an array like this:
{
"general_array":[
{"key_1":["a","b","c"]}
]
}
My goal is to add a new element to the array, for example:
{"key_2":["d","e","f"]}
The value of the new key comes from a variable:
var newKey = 'key_2';
I attempted to add the element to the existing array using this code snippet:
// ... obtaining file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
jsonObj.general_array.push({newKey:['d','e','f']});
var newJsonFileContent = JSON.stringify(jsonObj);
// rewriting the file ...
// console.log(newJsonFileContent);
However, the resulting file shows:
{
"general_array":[
{"key_1":["a","b","c"]},
{"newKey":["d","e","f"]}
]
}
Instead of the value of the variable, the name of the variable is added as a new element key.
How can I add the actual value?
UPDATED
The method using [newKey]
functions in most browsers but not in Internet Explorer 11.
I require a solution that works across all browsers, including IE11. This query remains unresolved.