I got a JSON string with an array like this:
{
"Id": 123,
"Username": "Sr. X",
"Packages": [
{
"Name": "Cups",
"SupplierId": 1,
"ProviderGroupId": 575,
"SupplierName": "Foo Cups"
},
{
"Name": "Pins",
"SupplierId": 5,
"ProviderGroupId": 1082,
"SupplierName": "Foo Pins"
}
]
}
and I want to add a new field into Packages array like:
"Packages": [
{
"Name": "Cups",
"SupplierId": 1,
"ProviderGroupId": 575,
"SupplierName": "Foo Cups",
"New Field": "Value"
},...
Right now I can add a new field but in the main object, I'm using Json.NET library to do the job, but it seems that the documentation doesn't reach that level.
Have any one of you done it before?
JObject implemets IDictionary.
var jObj = JObject.Parse(json);
foreach(var item in jObj["Packages"])
{
item["New Field"] = "Value";
}
var newjson = jObj.ToString(Newtonsoft.Json.Formatting.Indented);
Try
JObject root = (JObject) JsonConvert.DeserializeObject(File.ReadAllText("products.json"));
JArray packages = (JArray) root["Packages"];
JObject newItem = new JObject();
newItem["Name"] = "Cups";
// ...
packages.Add(newItem);
Console.WriteLine(root); // Prints new json
Related
I try to delete information from a JSON but when i put the og JSON to a new variable and then delete some of the information from both
example:
fs = require('fs');
var name = 'Assets/signup.json';
var m = JSON.parse(fs.readFileSync(name).toString());
const originalJSON = m;
let newJSONFile = originalJSON;
console.log(originalJSON)
newJSONFile.members.splice(0, newJSONFile.members.length)
console.log(originalJSON)
so this code should from what i know that it will asign a new JSON and then delete the members from newJSONFile and keep the members in the originalJSON but when i console.log(originalJSON) it output the members to be empty and i dont understand why
What looks like is your newJSONFile and originalJSON are both the same.
The objects in JS, they refer to same location. Unlike primitives we cant make a copy simply by using =. You can read more about it here
We can create deep copies using spread and other ways const newJSONFile = {...originalJSON} but this will still not deep copy the nested objects.
I am not aware of the structure your JSON is so can't suggest best way to create a deep copy.
You can use clone functions from libraries like lodash
UPDATED:
Create a deep clone of your original JSON, instead of just creating a reference. Then you can delete from the clone, and retain the original:
/* YOUR JSON FILE */
const newJSON = {
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
/* LOG OG JSON FILE */
console.log(newJSON);
/* DEEP CLONE JSON FILE - MAKES A COPY */
let deepCloneJSON = JSON.parse(JSON.stringify(newJSON));
/* DELETE FROM THE COPY, NOT THE ORIGINAL */
delete deepCloneJSON.members[1];
console.log(deepCloneJSON);
/* CHECK THE ORIGNAL IS STILL INTACT */
console.log(newJSON);
https://jsfiddle.net/pixelmedia/7j18y5sp/12/
Old responses due to vague question:
Your question seems rather confusing, but if you are trying to delete from your JSON, then use the following.
Example: This will delete the second, and leave the first (0).
delete originalJSON[1];
Another example:
Initial is: 1, 2, 3
const originalJSON = [1, 2, 3];
delete originalJSON[1];
console.log(originalJSON);
Expected output: 1, 3
Now updated to demonstrate with the additional information provided by the OP:
const newJSON = {
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
delete newJSON.members[1];
console.log(newJSON);
Expected output: removed 'Tinyruthless'
JSFiddle: https://jsfiddle.net/pixelmedia/7j18y5sp/1/
so my json will look like this:
{
"howToUse": ",,photos {name} {instagram}",
"date": "April 8, 2021",
"available": "true",
"members": [
{
"name": "TinyruthlessPC",
"instagram": "Xclusiv3_Tester",
"signupDate": "April 10, 2021"
},
{
"name": "Tinyruthless",
"instagram": "Xclusiv3_Photography",
"signupDate": "April 10, 2021"
},
{
"name": "Kade",
"instagram": "Kade_Sucks",
"signupDate":"April 11, 2021"
}
]
}
and i want to make it so that i can go through it and then delete one of the members and keep the rest in the same order
so i thought that i could just do
console.log(`deleteing person`)
fs = require('fs');
var name = 'Assets/signup.json';
var m = JSON.parse(fs.readFileSync(name).toString());
const originalJSON = m;
let newJSONFile = originalJSON;
console.log(originalJSON)
newJSONFile.members.splice(0, newJSONFile.members.length)
console.log(originalJSON)
for(m in originalJSON.members) {
console.log(`for loop runs`)
if(originalJSON.members[m]['name'] !== args[0]) {
let addMember = {
"name": originalJSON.members[m]['name'],
"instagram": originalJSON.members[m]['instagram'],
"signupDate": originalJSON.members[m]['signupDate']
}
newJSONFile.members.push(addMember)
console.log(newJSONFile)
}else {
}
}
and it just deletes it from both
Hi I used below script for this scenario.
const orgObj = { foo: "foo", bar: [1, 2, 3] }
var clonedObj = Object.assign({}, orgObj);
clonedObj.bar = Array.from(clonedObj.bar);
clonedObj.bar.push(4);
console.log(orgObj)
console.log(clonedObj)
It will make complete saperate copy of you object and OrgObj will remain unchanged.
I'm trying to add an object into an empty array that is stored in one of my collections.
Currently this is how I have my collection setup:
[
{
"name": "user_added",
"DRGs": []
},
...
]
How can I insert an object into the collection so that it looks like this;
[
{
"name": "user_added",
"DRGs": [
{
"code": "491",
"name": "Back & neck procedures"
}
]
},
...
]
Check out $push documentation.
You should be able to accomplish your goal with the following:
var collectionName = 'users'; // or whatever your actual collection name is
var objectToPush = {
code: "491",
name: "Back & neck procedures"
};
db.collection(collectionName).updateOne(
{"name": "user_added"},
{ $push: { "DRGS": objectToPush }}
);
I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my problem...
for(i=0;i<duplicates.length; i++) {
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
I take object properties from the duplicates array that can have the following elements:
[{scopeDef=.*, scope=Global, variable=[trackingcode, v1, v2]}, {scopeDef=^https?://([^/:\?]*\.)?delta.com/products, scope=Products Section, variable=[v3]}]
As you can see, an object contain variable element that can have multiple values. I need to push to the JSON object all those values dynamically (meaning that there could be more than 3 values in an array).
For example, after I push all the values from the duplicates array, my JSON object should look like this:
name=Products Section,
rules=
[
{
name=Products Section OP SDR Sync,
tags=[
{
variables=
[
{
matchType=Regex,
variable=v3,
value=^https?://([^/:\?]*\.)?delta.com/products
},
{
matchType=Regex,
variable=trackingcode,
value=.*
},
{
matchType=Regex,
variable=v1,
value=.*
},
{
matchType=Regex,
variable=v2,
value=.*
}
],
condition=false,
},
{
condition=false,
tagId=1
}
],
ruleSetId=3
}
]
}
I tried the following code but without success:
for(var j in duplicates[i].variable) {
var append = JSON.parse(request);
append['variables'].push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
}
Please let me know if I need to provide additional information, I just started working with JSON objects.
First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:
var json='{"a":"1", "b":"2"}';
var x = JSON.parse(json);
Next, you have any property of object wrapped in arrays. To correctly work with it you should write:
request.rules[0].tags[0].variables.push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
If you want to use your code snippet, you need some changes in request:
var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
To understand JSON remember basic rule: read JSON backward. It means:
property
object.property
arrayOfObfects['id'].object.property
mainObject.arrayOfObfects['id'].object.property
and so on. Good luck!
I have a JSON response from my API that is structured like so:
{
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
When I reference data I get the array with each record. I need the curly braces to be brackets due to a plugin I am using requiring it to be an array.
Desired output:
[
["1", "test"],
["2", "test"]
]
How can I convert the above JSON to this?
Edit:
This turned out to be a problem with a plugin I was using, and I knew how to do this fine all along. Thought I was going crazy but my code was fine, some plugin was screwing things up.
You can do this using Array.prototype.map
var arr = json.data.map(function(x){
return [x.id, x.name];
});
Something like this maybe: http://jsfiddle.net/3gcg6Lbz/1/
var arr = new Array();
var obj = {
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
for(var i in obj.data) {
var thisArr = new Array();
thisArr.push(obj.data[i].id);
thisArr.push(obj.data[i].name);
arr.push(thisArr);
}
console.log(arr);
Is there a way to build object constructors from a JSON schema? I want to create a json schema associated with my application's namespace that I can edit once, and change the properties(before runtime) of my objects.
I know that you can write a pseudo classical object constructor like
var Note = function(input){
var title = input
};
var newNote = new Note("test title");
Is it possible to create a similar structure from json? Such that I can write:
var Note = {
"title":""
};
var newNote = new Note();
newNote.title = "test title"
I understand that this above is syntactically wrong, but I would like to for example have:
var notes = {
"NotesList":[{
"title":"note1",
"content":"test content"
}]
}
var newNote = new Note();
notes.NotesList.add(newNote);
newNote.title = "new title";
so that I can base all my objects and all of their children off of this object template created from my json schema. If this is not possible, can you recommend a better method?
I'm not sure that I understood your question completely. However if you wish to convert a function into JSON then yes, that's definitely possible.
All you need to do is use a JavaScript parser like acorn which uses the Mozilla Parser API to generate an abstract syntax tree of your constructor in JSON format. For example:
var ast = acorn.parse(Note);
var json = JSON.stringify(ast, null, 4);
alert(json);
function Note(input) {
var title = input;
}
See the demo here. The above code produces the following output:
{
"type": "Program",
"start": 0,
"end": 47,
"body": [
{
"type": "FunctionDeclaration",
"start": 0,
"end": 47,
"id": {
"type": "Identifier",
"start": 9,
"end": 13,
"name": "Note"
},
"params": [
{
"type": "Identifier",
"start": 14,
"end": 19,
"name": "input"
}
],
"body": {
"type": "BlockStatement",
"start": 21,
"end": 47,
"body": [
{
"type": "VariableDeclaration",
"start": 27,
"end": 44,
"declarations": [
{
"type": "VariableDeclarator",
"start": 31,
"end": 44,
"id": {
"type": "Identifier",
"start": 31,
"end": 36,
"name": "title"
},
"init": {
"type": "Identifier",
"start": 39,
"end": 44,
"name": "input"
}
}
],
"kind": "var"
}
]
}
}
]
}
You can save the above AST in a JSON file and load it as and when required. You can use escodegen to convert the AST back to JavaScript as follows:
alert(escodegen.generate(ast));
See the demo here. You may then eval the generated code and use the Note constructor as you wish.
I found the answer to what I was looking for. My ultimate goal was to make an object with arrays of children, each of which could have children etc. The object would then be used as the namespace to my entire application like:
var myobj = {};
I wanted to use JSON to specify the properties of this object, and then build constructors off of these properties like:
var myObj = {
"name": "genericname",
"id": "uniqueid",
"children": [
{
"grandchildren": [
{
"name": "child",
"age": "0"
}
]
}
]
};
What I ended up doing was, building constructor functions from this, and then cloning them into my new objects so they could have these default values like this:
myObj.Child = function(){
var child = myObj.children[0];
return child;
//this is the unmodified constructor child
};
var myObj.createChild = function(){
var newChild = new Clone(myObj.Child());
//do stuff to this is new child which can be modified without changing the original
return newChild;
};