I'm trying to parse json object to get the key and value concatenated to a variable.
My desired output from the given json is:
"/" - 7.84 GiB; "/opt" - 4.86 GiB; "/usr" - 4.80 GiB
Using my snippet i can get objects but struggling to get the name and value in desired format. Please assist.
for (i = 0; i < obj.length; i++)
{
if ( obj[i].name === 'mountpoints')
{
js_mountpoints = obj[i].value;
break;
}
js_mountpoints = 'NA';
}
My JSON input:
[{
"name" : "pe_build",
"value" : "2016.2.1"
},
{
"name" : "kernel",
"value" : "Linux"
}, {
"name" : "blockdevices",
"value" : "sda,sdb,sr0"
},
{
"name" : "mountpoints",
"value" : {
"\/boot\/efi" : {
"size_bytes" : 261861376,
"size" : "249.73 MiB",
"capacity" : "0%"
},
"\/opt" : {
"size_bytes" : 2086666240,
"size" : "1.94 GiB",
"capacity" : "1.64%"
},
"\/boot" : {
"size_bytes" : 258650112,
"size" : "246.67 MiB",
"capacity" : "74.28%"
},
"\/var" : {
"size_bytes" : 10475274240,
"size" : "9.76 GiB",
"filesystem" : "xfs",
"capacity" : "4.01%"
}
}
}, {
"name" : "uptime_seconds",
"value" : 244181
}, {
"name" : "memoryfree",
"value" : "6.66 GiB"
}, {
"name" : "memoryfree_mb",
"value" : 6816.91796875
}
]
finalStr = ''
Object.keys(obj).forEach(function(key) {
if (obj[key].name === 'mountpoints') { // only get sizes for mountpoints
var value = obj[key].value;
Object.keys(value).forEach(function(name) { // add all sizes to string
finalStr += '"' + name + '" - ' + value[name].size + ';';
}); //update
}
}); //update
if (finalStr.length > 0) { // at least one entry was added
finalStr.slice(0, -1);
}
Related
Here is MongoDB scheme.
{
"_id" : ObjectId("222222"),
"active" : false,
"amount" : "15%",
"description" : "15% discount",
"name" : "20200628-test",
"policies" : {
"apply" : [
{
"name" : "expiryDate",
"params" : {
"date" : ISODate("2020-07-06T14:59:59.999Z")
}
},
{
"name" : "isApplyCategoryExist"
}
],
"discount" : [],
"conflict" : [
{
"name" : "exclusive"
}
],
"grant" : []
},
"target" : {
"sku" : "",
"products_ids" : [],
"category_ids" : [
ObjectId("11111111")
]
},
"title" : "15% coupon"
}
I want to access date.
For example, "policies.apply.params.date"...
I don't know how to access 'date' to Javascript.
Please let me know...
apply is an array, so you have to give it index which you want to get.
var num = 0; // pick up an array number you want
var date = policies.apply[num].params.date;
Your policies.apply is an array so if you want to access "2020-07-06T14:59:59.999Z", you should do this:
policies.apply[0].params.date
But the "policies.apply[1]" doesn't have params (params.date also) so you can write a function to get date like this:
function get_apply_date(index) {
if(policies.apply[index].params && policies.apply[index].params.date)
return policies.apply[index].params.date;
return undefined; // or null
}
Need help on operation like update,delete,add,upsert,delete on below document of MongoDB.
Below is MongoDB document that exists in temp collection.
{
"local_id" : "1841",
"name_first" : "tiger",
"name_last" : "lion",
"address" : [
{
"id" : 1,
"address_type" : "Home",
"city" : "Delhi",
"country" : "",
"po_box" : ""
},
{
"id" : 2,
"address_type" : "Work",
"city" : "",
"country" : "",
"po_box" : ""
}
],
"email" : [
{
"email_id" : "blah#gmail.com",
"id" : 1,
"type" : "Home"
},
{
"email_id" : "Pearl1#gmail.com",
"id" : 2,
"type" : "Work"
}
],
"phone_number" : [
{
"id" : 1,
"no" : "+911234567890",
"type" : "Mobile"
},
{
"id" : 2,
"no" : "+917894561230",
"type" : "work"
}
]
}`
Now I have some document like below, i want query that will compare,add,update,delete on my above document.
`
{
"local_id" : "1730",
"name_first" : "lion",
"name_last" : "king",
"address" : [
{
"id" : 1,
"address_type" : "Home",
"city" : "Delhi",
"country" : "India",
"po_box" : "110041"
},
{
"id" : 2,
"address_type" : "Work",
"city" : "Delhi-NCR",
"country" : "India",
"po_box" : "110048"
},
{
"id" : 3,
"address_type" : "Work",
"city" : "Delhi-NCR",
"country" : "Indai",
"po_box" : "110048"
}
],
"email" : [
{
"email_id" : "updatethis#gmail.com",
"id" : 1,
"type" : "Home"
},
{
"email_id" : "Pearl1#gmail.com",
"id" : 2,
"type" : "Work"
},
{
"email_id" : "addthisarray#gmail.com",
"id" : 3,
"type" : "personal"
}
],
"phone_number" : [
{
"id" : 1,
"no" : "+911234567890",
"type" : "Mobile"
}
/*second array not here so remove that array from that document*/
]
}`
You can save function on server as you can call that function to get the differences, as below.
db.system.js.save({
_id: "getupdatedArray",
value: function(obj1, obj2) {
var VALUE_CREATED = 'created';
var VALUE_UPDATED = 'updated';
var VALUE_DELETED = 'deleted';
var VALUE_UNCHANGED = 'unchanged';
function map(obj1, obj2) {
if (isValue(obj1) || isValue(obj2)) {
return {
type: compareValues(obj1, obj2),
old: obj1,
new: obj2
};
}
var diff = {};
for (var key in obj1) {
if (isFunction(obj1[key])) {
continue;
}
var value2 = undefined;
if ('undefined' != typeof(obj2[key])) {
value2 = obj2[key];
}
diff[key] = map(obj1[key], value2);
}
for (var key in obj2) {
if (isFunction(obj2[key]) || ('undefined' != typeof(diff[key]))) {
continue;
}
diff[key] = map(undefined, obj2[key]);
}
return diff;
}
function compareValues(value1, value2) {
if (value1 === value2) {
return VALUE_UNCHANGED;
}
if ('undefined' == typeof(value1)) {
return VALUE_CREATED;
}
if ('undefined' == typeof(value2)) {
return VALUE_DELETED;
}
return VALUE_UPDATED;
}
function isFunction(obj) {
return {}.toString.apply(obj) === '[object Function]';
}
function isArray(obj) {
return {}.toString.apply(obj) === '[object Array]';
}
function isObject(obj) {
return {}.toString.apply(obj) === '[object Object]';
}
function isValue(obj) {
return !isObject(obj) && !isArray(obj);
}
return map(obj1, obj2);
}
})
Then you can call function as below..
db.loadServerScripts();
getupdatedArray({"a": "abc"}, {"a": "a111", "b": "bbb"});
This will give you result as below:
{
"a" : {
"type" : "updated",
"old" : "abc",
"new" : "a111"
},
"b" : {
"type" : "created",
"old" : undefined,
"new" : "bbb"
}
}
Thanks
Satish Lakhani
I'm trying to read data from an array in JSON with javascript but I can't get it working. This is the segment of the JSON file from wich I want to read the data, I want to read the age variable from different arrays:
{
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" :
[
{
"result" :
{
duration : 0.97834,
empty : false,
suites :
[
cases :
[
{
"age" : 0,
"status" : Passed
}
{
"age" : 15,
"status" : Passed
}
{
"age" : 3,
"status" : failed
}
]
]
}
}
]
}
I've tried this:
for (var i = 0; i < jsonData.childReports.suites.cases.length; i++)
{
var age = jsonData.childReports.suites.cases[i];
}
But it doesn't work. What would be the best way to do this?
Thanks in advance,
Matthijs.
Try the following code:
for (var i = 0; i < jsonData.childReports[0].result.suites[0].cases.length; i++) {
var age = jsonData.childReports[0].result.suites[0].cases[i].age;
}
Correct Json:
{
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" : [
{
"result" : {
duration : 0.97834,
empty : false,
suites : [{
cases : [
{
"age" : 0,
"status" : "Passed"
},
{
"age" : 15,
"status" : "Passed"
},
{
"age" : 3,
"status" : "failed"
}
]}
]
}
}]
}
This way you can achieve that :
var data = {
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" : [
{
"result" : {
duration : 0.97834,
empty : false,
suites : [{
cases : [
{
"age" : 0,
"status" : "Passed"
},
{
"age" : 15,
"status" : "Passed"
},
{
"age" : 3,
"status" : "failed"
}
]}
]
}
}]
};
for (var i = 0; i < data.childReports[0].result.suites[0].cases.length; i++) {
console.log(data.childReports[0].result.suites[0].cases[i].age);
}
DEMO
Not sure if I'm repeating the question or concept.
How do I convert the below sample to the below string format (may not be correct JSON format)
[{ "Name":"Test1","check":"true},{ "Name":"Test2","check":"true},{ "Name":"Test3","check":"false"}]
string format with appending - for false
Expected o/p:
"Test1","Test2","-Test3"
I have tried concatenating, but it always ends up with
"Test1,Test2-Test3"
But I am looking for 3 separate string separated by comma. Any hint would help
You can simply iterate through your array and collect the object in your required format:
var obj = [{
"Name" : "Test1",
"check" : true
}, {
"Name" : "Test2",
"check" : true
}, {
"Name" : "Test3",
"check" : false
}
];
var result = obj.map(function(x) {
return x.check ? x.Name : "-" + x.Name;
});
document.body.innerHTML = JSON.stringify(result);
Note that I have changed the format of your JSON in order to make it valid.
Just in case if you actually have a string true and false, and you can't change this, you can simply compare it as a string:
var obj = [{
"Name" : "Test1",
"check" : "true"
}, {
"Name" : "Test2",
"check" : "true"
}, {
"Name" : "Test3",
"check" : "false"
}
];
var result = obj.map(function(x) {
return x.check === 'true' ? x.Name : "-" + x.Name;
});
document.body.innerHTML = JSON.stringify(result);
HTML
<div id="output"></div>
Javascript
var obj = [{
"Name" : "Test1",
"check" : true
}, {
"Name" : "Test2",
"check" : true
}, {
"Name" : "Test3",
"check" : false
}
];
function getNames(){
var length=obj.length;
// alert(length);
var op=[];
for(var i=0;i<obj.length;i++){
// alert(obj[i].Name);
op[i]='"'+obj[i].Name+'"';
}
document.getElementById("output").innerHTML=op;
}
getNames();
Your output is there as expected.
Just loop through the valid JSON array(obj) and append the required values(obj.Name) to the empty string(str) based on the condition(appending '-' for 'false' value of obj.check).
var obj = [{
"Name" : "Test1",
"check" : true
}, {
"Name" : "Test2",
"check" : true
}, {
"Name" : "Test3",
"check" : false
}
];
var str = '';
for(var x in obj){
str += (obj[x].check === true) ? obj[x].Name : '-'+obj[x].Name;
str += (x != (obj.length-1)) ? ',' : '';
}
alert(str);
I am looking for a way to sort my three main JSON keys (neutral, positive, negative) using their children y-keys' values.
This is how the JSON object is set up:
{
"chartSeries" : {
"negative" : [ {
"y" : 1505,
"url" : "http://www.test.com/1"
}, {
"y" : 425,
"url" : "http://www.test.com/2"
}, {
"y" : 1046,
"url" : "http://www.test.com/3"
} ],
"neutral" : [ {
"y" : 10,
"url" : "http://www.test.com/4"
}, {
"y" : 1,
"url" : "http://www.test.com/5"
}, {
"y" : 2,
"url" : "http://www.test.com/6"
} ],
"positive" : [ {
"y" : 230,
"url" : "http://www.test.com/7"
}, {
"y" : 50,
"url" : "http://www.test.com/8"
}, {
"y" : 483,
"url" : "http://www.test.com/9"
} ]
}
}
Let's say I want to sort the negative values descending by y's value, then my JSON should look like this:
{
"chartSeries" : {
"negative" : [ {
"y" : 1505,
"url" : "http://www.test.com/1"
}, {
"y" : 1046,
"url" : "http://www.test.com/3"
}, {
"y" : 425,
"url" : "http://www.test.com/2"
} ],
"neutral" : [ {
"y" : 10,
"url" : "http://www.test.com/4"
}, {
"y" : 2,
"url" : "http://www.test.com/6"
}, {
"y" : 1,
"url" : "http://www.test.com/5"
} ],
"positive" : [ {
"y" : 230,
"url" : "http://www.test.com/7"
}, {
"y" : 483,
"url" : "http://www.test.com/9"
}, {
"y" : 50,
"url" : "http://www.test.com/8"
} ]
}
}
note how the negative elements are ordered by their descending y-values and neutrals' and postives' values are ordered exactly in the same sequence.
I tried parsing it as Javascript object using JSON.parse() and then using a sort function:
function sortResults(data, prop, asc) {
sorted_data = data.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]);
else return (b[prop] > a[prop]);
});
return sorted_data;
}
But I just get "TypeError: data.sort is not a function" in my debugger.
Any explanations or advices are kindly appreciated!
And do not forget to add a paseInt() to ensure all the keys are integers. I had somy funny time figuring that back in the days.
I'll stick with JSON.sortify (https://www.npmjs.com/package/json.sortify) as it perfectly suits my needs.
The code behind that magical function:
function sortKeys(o) {
if (Array.isArray(o)) {
return o.map(sortKeys)
} else if (o instanceof Object) {
var _ret = function() {
var numeric = [];
var nonNumeric = [];
Object.keys(o).forEach(function(key) {
if (/^(0|[1-9][0-9]*)$/.test(key)) {
numeric.push(+key)
} else {
nonNumeric.push(key)
}
});
return {
v: numeric.sort(function(a, b) {
return a - b
}).concat(nonNumeric.sort()).reduce(function(result, key) {
result[key] = sortKeys(o[key]);
return result
}, {})
}
}();
if (typeof _ret === "object") return _ret.v
}
return o
};
And that's it.