I have a large nested JSON response in following sample format:
{
"type": "folder",
"path": "Path1",
"owner": "user1",
"entries": [{
"type": "folder",
"path": "Path2",
"owner": "user1",
"entries": [{
"type": "folder",
"path": "Path3",
"owner": "user1"
},
{
"type": "file",
"path": "FullFilePath1",
"owner": "user1"
}
]
}]
}
I wanted to extract all the file type with selected keys and also add additional keys:
{
"type": "file",
"path": "FullFilePath1",
"Application": "My Application",
"UpdatedTime": "Time"
}
I am using nodejs. I need inputs in parsing the JSON file in best way. I was trying to check if I can use JSON Schema and Classes to do this but still didnt get through.
Could you please guide me?
Since you are dealing with JSON, you can simply load it into a JavaScript variable using require:
let data = require('./data.json');
You can then loop the variable for all entries tag
let fileData = require('./data.json');
let allEntries = [];
loadEntries(fileData);
function loadEntries(data) {
if(data.entries) {
for (let index = 0; index < data.entries.length; index++) {
const entry = data.entries[index];
// Do something with the entry
allEntries.push(entry);
loadEntries(entry);
}
}
}
Related
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.
I am trying to retrive some data from nested object.
This is the consle.log() result:
console.log("bg data", data)
{
"pageLayouts": {
"data": [
{
"attributes": {
"title": "a title",
"layout": "home",
"backgroundImage": {
"data": [
{
"attributes": {
"alternativeText": "bg image",
"url": "image url",
"__typename": "UploadFile"
},
"__typename": "UploadFileEntity"
}
],
"__typename": "UploadFileRelationResponseCollection"
},
"__typename": "PageLayout"
},
"__typename": "PageLayoutEntity"
}
],
"__typename": "PageLayoutEntityResponseCollection"
}
}
What i need is the URL.
What i tried:
const backgroundImage = attributes?.pageLayouts?.data?.attributes.backgroundImage.data?.attributes?.url
plz if anyone knows what i am missing here.
Thanks
Erhm, if console.log(data); outputs what you posted, then you should use data:
const backgroundImage = data?.pageLayouts?.data?.attributes.backgroundImage.data?.attributes?.url
Edit: Missed the array parts (thanks Steve Hynding), but again, if console.log(data); outputs what you posted, use data:
const backgroundImage = data?.pageLayouts?.data?.[0].attributes.backgroundImage.data?.[0].attributes?.url
The data objects are Arrays but you are trying to read the properties as if it was just an object. You can still use unknown (?.) identifiers, you just need to do so on the array indices as such:
const backgroundImage = attributes?.pageLayouts?.data?.[0]?.attributes.backgroundImage.data?.[0]?.attributes?.url
Note the addition of ?.[0] to both data objects.
I have 2 different Json files
1: a Deaflut JSON file
2: A Product Based JSON file
I need to merge them together in such a way that if a feature in default is not in a product that needs to be added to product config from default one.
for this merge, I used "lodash.mergewith" https://www.npmjs.com/package/lodash.mergewith.
so this is now taking care of the merge, But the file contains multiple nested JSON arrays inside it.
to handle that there is an option to use a customizer method that can handle array merge as mentioned in the usage of lodash.mergewith. I need a customizer that can find the Label from Deaflut and compare it with the Product if the Product has the same Label value then replace the URL with the Product URL. else if the Label is not in Product config, then use it from default as it is.
Example
Default config.json:-links is an array of this json with path : object►login►options►sections►2►links
"links": [{
"url": "www.google.com",
"label": "Lable1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
Productconfig.json:- links is an array inside this of the path: object►login►options►sections►2►links
"links": [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
]
** after merge mergedconfig.json "Links" need to be like this.**
"links": [{
"url": "www.product1.com",
"label": "Label1"
},
{
"url": "www.product2.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
The main concern is this Array is coming inside a JSON file inside some JSON objects
like eg if the Array is inside links[] it will be in a path like : object►login►options►sections►2►links[]. and this Links Array similarly present inside in some other paths eg: object►register►options►sections►2►links[]
So I need to figure out all the Array like this and for each of the Arrays, I need to perform this action.
Just use Array.map and Array.find:
let links= [
{
"url": "www.google.com",
"label": "Label1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
];
let plinks= [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
];
let results = links.map(lnk=>{
plnk = plinks.find(pl=>pl.label.toLowerCase()===lnk.label.toLowerCase());
return plnk || lnk
});
console.log(results);
for clean access to nested JSON keys you can use ES like this:
let a = {
b: {
c: [1,2,3]
}
};
let {c} = a?.b;
console.log(c);
I have the following problem, I want to update a document with a path id.metadata.panels.items where panels is an array and items is an array. My search query looks at the items and displays only those that match the criteria of metadata.panels.items.member.type: 'owner' - then I want to update the 'owner to 'account'.
When I am trying to update having the search path same as update path I get an error message saying: cannot use the part metadata.panels.items.member.type to traverse the element.
The documents have their own
How can I resolve this problem?
I have already tried to go through the collection using nested forEach statements to iterate through each of the arrays but I am not sure what to do next.
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
var newFields = [];
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
})
})
})
Sample document structure:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Owner]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
Expected result:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Account]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
I figured it out.
var newFields = [];
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
// I have generated update statements as strings
// first list is always position 0 and this goes to the statement
// second list get's populated from itemIndex
// added them to the newFields list
})
})
})
newFields.forEach(function(i){
eval(i)
})
I have a JSON Array inside my Node.js code with the following schema:
{
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
}
and I want to add data so it will look like:
{
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z",
"information": "someInformation"
}
]
}
Can you help me how to do this?
Thanks!
Like this? access the data property, of the obj variable, and the first element in that array, then set a new property on that object equal to your string.
var obj = {
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
};
obj.data[0].information = "someInformation";
console.log( obj );
Since you have already the JSON you should firstly parse it, because JSON is a string. After parsing you will get object that should be saved in some variable, then you can access it as general object and add the property you want. Then you have to transform it to JSON string again. It will be like this
var parsed = JSON.parse(data); // Now we are transforming JSON string into the object
//Now you may do whatever you want
parsed.newprop = 'some text';
parsed.hello = 'Hellow world';
data = JSON.stringify(parsed); // Now we are replacing the previous version of JSON string to new version with additional properties
var dataContainer = {
"status": "ok",
"data": [
{
"id": 1,
"active": true,
"createdAt": "2017-07-21T15:39:31.000Z",
"updatedAt": "2017-07-21T15:47:13.000Z"
}
]
};
for(var i = 0; i < dataContainer.data.length; i++) {
dataContainer['data'][i]['information'] = "some information";
}
Hope it helps you !