Dynamically Add Variable Name Value Pairs to Json Object

Dynamically Add Variable Name Value Pairs to JSON Object

That's not JSON. It's just Javascript objects, and has nothing at all to do with JSON.

You can use brackets to set the properties dynamically. Example:

var obj = {};
obj['name'] = value;
obj['anotherName'] = anotherValue;

This gives exactly the same as creating the object with an object literal like this:

var obj = { name : value, anotherName : anotherValue };

If you have already added the object to the ips collection, you use one pair of brackets to access the object in the collection, and another pair to access the propery in the object:

ips[ipId] = {};
ips[ipId]['name'] = value;
ips[ipId]['anotherName'] = anotherValue;

Notice similarity with the code above, but that you are just using ips[ipId] instead of obj.

You can also get a reference to the object back from the collection, and use that to access the object while it remains in the collection:

ips[ipId] = {};
var obj = ips[ipId];
obj['name'] = value;
obj['anotherName'] = anotherValue;

You can use string variables to specify the names of the properties:

var name = 'name';
obj[name] = value;
name = 'anotherName';
obj[name] = anotherValue;

It's value of the variable (the string) that identifies the property, so while you use obj[name] for both properties in the code above, it's the string in the variable at the moment that you access it that determines what property will be accessed.

Dynamically add multiple key value pair in a json array in bash

Hardcoded records to add:

jq '
. + [
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
]
' file.json

Records to add provided as an argument:

jq --argjson to_add '
[
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
]
' '. + $to_add' file.json

Records to add provided as a file:

jq --argfile to_add to_add.json '. + $to_add' file.json

or

jq --slurp add file.json to_add.json

Dynamically add key value pair in jSON object using shell

First, when specifying a key name using a variable in the way you are doing, the variable must be parenthesized, so you would have:

 {($bundle_release): ...}

Next, jq variables are not the same as shell variables and should be specified without quoting them, and without using bash-isms.

Third, when setting the value of the shell variable named value, you would have to quote the expression appropriately.

Fourth, to simplify things, use --argjson for $value.

Fifth, your sample JSON is not quite right. Once it's fixed, the following will work in a bash or bash-like environment (assuming you're using a version of jq that supports --argjson):

bundle_release="1034,567"
value='{"release":"2018.1006","kernel":"2.6.32-754.3.5.el6.x86_64","os":"6.10","current":true}'

jq --arg b "$bundle_release" --argjson v "$value" '
. + {($b): $v}' <<< "$version6json"

How frame Json object dynamically with dynamic key and value strings

Firstly a little clarification; there's no such thing as a 'JSON object'. There is a JSON-formatted string, and there is an object. They are two separate entities.

To add strings to an object, specify the property of the object and set its value. You don't need push() for this as that is used exclusively for arrays. In your case, it should look like this:

var obj = {};
obj.key1 = "value1";
obj.key2 = "value2";
console.log(obj); // = { "key1": "value1", "key2": "value2" }

To set a key dynamically use bracket notation:

var key = 'foo';
obj[key] = 'bar';
console.log(obj); // = { 'foo': 'bar' }

If you need to then convert the object to a JSON string, call JSON.stringify on that object:

var json = JSON.stringify(obj);

Also note that in your second example you end up with an array of strings, not an array of objects. If you want an array of objects you need to remove the quotes around the values you set, like this:

var array = [];
var c = { "key1": "value1" };
var d = { "key2": "value2" };
array.push(c);
array.push(d);
console.log(array); // [{ "key1": "value1" }, { "key2": "value2" }]

Note the difference in the position of the quotes in the objects and the result from the console.

Is it possible to add dynamically named properties to JavaScript object?

Yes.

var data = {    'PropertyA': 1,    'PropertyB': 2,    'PropertyC': 3};
data["PropertyD"] = 4;
// dialog box with 4 in italert(data.PropertyD);alert(data["PropertyD"]);

Add dynamic key-values to JSON object

You are doing it wrong.
In forloop just change this syntax

var finalJSONObj={};
for loop(int i = 0; i<10;i++){
// gets the values of rows i need to add ..
finalJSONObj['task'+ (i + 1)] = tasks[i]; // need to add this in the JSON Object
}

Here key will be task + i which will be task1, task2 etc and value will be mapped to this key from your tasks array.

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }


Related Topics



Leave a reply



Submit