JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
Answer from Paul S. on Stack Overflow Top answer 1 of 6
303
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
2 of 6
29
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
Videos
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
CodeSpeedy
codespeedy.com › home › how to add elements in json array using javascript
How To Add Elements In JSON Array Using JavaScript - CodeSpeedy
July 17, 2021 - const fs = require("fs"); //The object to be added const addition = { name: "Anjan", description: "This is an example for CodeSpeedy", }; fs.readFile("./code.json", "utf8", function readFileCallback(err, data) { if (err) { console.log(err); } else { var obj = JSON.parse(data); //now converting it to an object obj.notes.push(addition); //adding the data var json = JSON.stringify(obj, null, 2); //converting it back to json fs.writeFile("./code.json", json, "utf8", (err) => { if (err) { console.log(err); } else { console.log("Done"); } }); } });
Robotastemtraining
robotastemtraining.com › read › how-do-you-add-elements-to-a-json-array
How do you add elements to a JSON Array?
The push() method adds one or more elements to the end of an array and returns the new length of the array. Here’s how you can use it: let fruits = ["Apple", "Banana", "Cherry"]; console.log("Before:", JSON.stringify(fruits)); fruits.push("Date"); console.log("After:", JSON.stringify(fruits));
Top answer 1 of 3
54
Observation
- If there is a single object and you want to push whole object into an array then no need to iterate the object.
Try this :
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
data.push(feed);
console.log(data);
Instead of :
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
for(var i in my_json) {
data.push(my_json[i]);
}
console.log(data);
2 of 3
1
You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
//["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
});
console.log(data);
GeeksforGeeks
geeksforgeeks.org › javascript-how-to-add-an-element-to-a-json-object
How to Add an Element to a JSON Object using JavaScript? | GeeksforGeeks
August 27, 2024 - Below are the approaches to conditionally adding a me ... JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we ar ... In this article, we will swap the key and value of JSON elements using JavaScript.
Top answer 1 of 3
1
HI,So basically you have to create a array and push this JSON into that array as below: · var obj1 = '{"app_said":"123","app_code":"AAA","application_type":"business","business_unit":"aaa","primary_email":"p@test.com","secondary_email":"s@test.com","manager_email":"m@test.com","description":"sd"}'; · var obj2 ='[{"s_type" : "physical","os" : "esx","f_type" : "application","region" : "emea","a_storage" : "100","r_required" : "false"}]'; · var arr = []; · arr.push(obj1);gs.print(arr); · arr.push(obj2);gs.print(arr); · · OUTPUT: · 2020-04-05T13:02:52.910Z: [ "{\"app_said\":\"123\",\"app_code\":\"AAA\",\"application_type\":\"business\",\"business_unit\":\"aaa\",\"primary_email\":\"p@test.com\",\"secondary_email\":\"s@test.com\",\"manager_email\":\"m@test.com\",\"description\":\"sd\"}" ] · 2020-04-05T13:02:52.910Z: [ "{\"app_said\":\"123\",\"app_code\":\"AAA\",\"application_type\":\"business\",\"business_unit\":\"aaa\",\"primary_email\":\"p@test.com\",\"secondary_email\":\"s@test.com\",\"manager_email\":\"m@test.com\",\"description\":\"sd\"}", "[{\"s_type\" : \"physical\",\"os\" : \"esx\",\"f_type\" : \"application\",\"region\" : \"emea\",\"a_storage\" : \"100\",\"r_required\" : \"false\"}]" ] · Thanks, · Ashutosh
2 of 3
0
Thanks much for the response. The other one was just worked fine. thanks
TutorialsPoint
tutorialspoint.com › article › how-to-add-an-element-to-a-json-object-using-javascript
How to add an element to a JSON object using JavaScript?
February 16, 2023 - var jsonObject = { members: { host: "hostName", viewers: { userName1: "userData1", userName2: "userData2" } } }; console.log("Original JSON object:"); console.log(jsonObject); console.log("\nAdding an element using dot notation:"); jsonObject.members.viewers.userName4 = 'userData4'; console.log("\nJSON object after adding property:"); console.log(jsonObject);
Redis
redis.io › docs › latest › commands › json.arrappend
JSON.ARRAPPEND | Docs
1 week ago - Add blue to the end of the colors array. JSON.ARRAPPEND returns the new length of the colors array. redis> JSON.ARRAPPEND item:1 $.colors '"blue"' 1) (integer) 3 · Get the updated value of the colors array. redis> JSON.GET item:1 $.colors "[[\"black\",\"silver\",\"blue\"]]" ... With $-based path argument: Array reply of integer replies or null replies, where each element is the array's new length, or null if the matching value is not an array.
Progress
docs.progress.com › bundle › abl-reference › page › Add-method-JsonArray.html
Add( ) method (JsonArray)
Skip to main contentSkip to search · Powered by Zoomin Software. For more details please contactZoomin

