JSON - Checking for a property in a deeply nested JSON - json

JSON structure:
{
"codes":[
{
"id":"1",
"code":{
"fname":"S",
"lname":"K",
"dateofbirth":{
"month":"12",
"day":"02",
"year":"1998"
}
}
},
{
"id":"2",
"code":{
"fname":"M",
"lname":"D",
"dateofbirth":{
"month":"10",
"day":"02",
"year":"1998"
}
}
}
]
}
I want to loop through each code AND dateofbirth and alert if the month is 12. If the month is not 12, then do nothing.
success: function(data){
var x;
for (x = 0; x < data.codes.length; x++){
var count=0;
for (property in data.codes[x].code) {
count++;
}
}
}
How can I loop through dateofbirth and check for the value of month?
Example of JSON structure with more than 1 property under 'code' that can be an object. So I want to loop through all the properties within code and check for the value of the month property instead of manually checking for a particular property.
{
"codes":[
{
"id":"1",
"code":{
"fname":"S",
"lname":"K",
"dateofbirth":{
"month":"12",
"day":"02",
"year":"1998"
},
"membership":{
"month":"12",
"day":"12",
"year":"2011"
}
}
},
{
"id":"2",
"code":{
"fname":"M",
"lname":"D",
"dateofbirth":{
"month":"10",
"day":"02",
"year":"1998"
},
"membership":{
"month":"10",
"day":"12",
"year":"2011"
}
}
}
]
}

mycodes=// the object from parsed JSON
for (i=0; i<mycodes.codes.length; i++) {
if (mycodes.codes[i].code.dateofbirth.month=="12") {
alert("Code " + mycodes.codes[i].id + " has birth month of 12");
}
}
BTW, you really should store birthdates as numbers, not strings.

Related

get difference between two dates in $project

Trying to project the date difference between two dates, but I am getting error -
Invalid $project :: caused by :: Unknown expression $dateDiff
db.books.aggregate([{
$project:{
Date_diff:
{$dateDiff:{
start_dt:'$borrowers_list.borrowed_dt',
endDate:'$borrowers_list.return_dt',
unit: "day"
}
}
}
}])
The json document structure is like this -
_id:6188a5283543f7cc2f77c73f
branch_id:1
borrowers_list:Object
0:Object
borrowed_dt:2021-08-15T06:00:00.000+00:00
card_no:"ID000067"
return_dt:2021-08-25T06:00:00.000+00:00
I have no idea why the error is unknown expression $dateDiff, as my syntax is correct. Does anyone have any suggestions?
Based on your provided JSON document, the document should be as below (correct me if it is incorrect):
{
_id: ObjectId("6188a5283543f7cc2f77c73f"),
branch_id: 1,
borrowers_list: {
0: {
borrowed_dt: ISODate("2021-08-15T06:00:00.000+00:00"),
card_no: "ID000067",
return_dt: ISODate("2021-08-25T06:00:00.000+00:00")
}
}
}
]
There is no start_dt in $dateFiff field, it is startDate.
Query
db.collection.aggregate([
{
$project: {
Date_diff: {
$dateDiff: {
startDate: "$borrowers_list.0.borrowed_dt",
endDate: "$borrowers_list.0.return_dt",
unit: "day"
}
}
}
}
])
Note: Above query will perform the $dateDiff for the first document in borrowers_list.
Sample Mongo Playground
In case you need to iterate each document (with key-value pair) in borrowers_list to perform $dateDiff.
$set - Convert from object to array (via $objectToArray) for borrowers_list to new field borrowers.
$set - Iterate each document in borrowers array (1) and perform $dateDiff.
$project - Decorate the output document, convert Date_diff from array to object (via $objectToArray).
Query
db.collection.aggregate([
{
$set: {
borrowers: {
"$objectToArray": "$borrowers_list"
}
}
},
{
$set: {
Date_diff: {
$map: {
input: "$borrowers",
as: "b",
in: {
k: "$$b.k",
v: {
$dateDiff: {
startDate: "$$b.v.borrowed_dt",
endDate: "$$b.v.return_dt",
unit: "day"
}
}
}
}
}
}
},
{
$project: {
Date_diff: {
"$arrayToObject": "$Date_diff"
}
}
}
])
Sample Mongo Playground (Iterate document with key-value pair)

How to map json entities?

There is a way to map json objects in react-native? For example, let's say I receive the following object:
{
"dados": {
"ultimaAtualizacao": {
"nome": "Lala"
}
"nascimento": "01/01/2001"
}
}
I want to map it like this:
{
"data": {
"lastUpdate": {
"name": "Lala"
}
"dob": "01/01/2001"
}
}
Considering that fetch returns the first object, this would be possible doing the following code:
myService.get(url).then(response => this.mapObject(response, []));
//Considering state is initialized and I have the mapedEntity to return correct properties
mapObject(jsonObject, parentProperty) {
for (let property in jsonObject) {
if (Array.isArray(jsonObject[property])) {
this.mapArray(jsonObject[property], [...parentProperty,property]); //Would be something like mapObject function
} else if (typeof jsonObject[property] === 'object') {
this.mapObject(jsonObject[property],[...parentProperty,property]);
} else {
let prop = this.state;
for(let k of parentProperty) {
prop = prop[mapedEntity[k]];
}
prop[entidadeMapeada[property]] = jsonObject[property];
}
}
}
There is someway simplier to achieve this?

Mongo: Move json string to a part of the document

I have a mongo collection where documents have aprox the following structure:
item{
data{"emailBody":
"{\"uniqueKey\":\" this is a stringified json\"}"
}
}
What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.
I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".
Is there a better way to handle stringified json in mongo?
The only way is to loop through the collection, parse the field to JSON and update the document in the loop:
db.collection.find({ "item.data.emailBody": { "$type": 2 } })
.snapshot().forEach(function(doc){
parsedEmailBody = JSON.parse(doc.item.data.emailBody);
printjson(parsedEmailBody);
db.collection.updateOne(
{ "_id": doc._id },
{ "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
);
});
For large collections, leverage the updates using the Bulk API:
var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
ops = [];
cursor.forEach(function(doc){
var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
}
});
if (ops.length === 500) {
db.collection.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) { db.collection.bulkWrite(ops); }

coldfusion json parsing issue

I have the following json string and need to extract each of the survey_id values as a list. ie 74448500, 74052991, 65442357
{
"status":0,
"data":{
"surveys":[
{
"survey_id":"74448500"
},
{
"survey_id":"74052991"
},
{
"survey_id":"65442357"
}
],
"page":1,
"page_size":1000,
"metadata":{
"collaboration":{
"shared_by_total":0,
"unfiled_owned_total":143,
"shared_with_total":0,
"owned_total":242
}
}
}
}
Not sure what version of ColdFusion you are on, here are two possible ways to do it:
<cfscript>
x = deserializeJSON('{"status":0,"data":{"surveys":[{"survey_id":"74448500"},{"survey_id":"74052991"},{"survey_id":"65442357"}],"page":1,"page_size":1000,"metadata":{"collaboration":{"shared_by_total":0,"unfiled_owned_total":143,"shared_with_total":0,"owned_total":242}}}}');
// ColdFusion 11
y = x.data.surveys.map(function(item){
return item.survey_id;
});
writeDump(arrayToList(y));
// ColdFusion 9+
z = [];
for (item in x.data.surveys) {
arrayAppend(z, item.survey_id);
}
writeDump(arrayToList(z));
</cfscript>

Parsing JSON multi-level array

I want to search in json data with multiple levels of array. My search list return names of my objects but just from the first level. How could i do return all my object's names regardless their levels ?
In this example : OST, OST details, Apocalpse Now, Arizona Dream, Dexter
Data
<script type="application/json" id="dataMusic">
{
"name":"Music",
"level":"1",
"size":36184,
"children":[
{
"name":"OST",
"level":"2",
"size":1416,
"children":[
{
"name":"OST details",
"level":"3",
"size":1416,
"children":[
{
"name":"Apocalypse Now",
"size":15
},
{
"name":"Arizona Dream",
"size":19
},
{
"name":"Dexter",
"size":20
}
]
}
]
}
]
}
</script>
Function
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var optArray = [];
for (var i = 0; i < dataTree.children.length - 1; i++) {
optArray.push(dataTree.children[i].name);
}
optArray = optArray.sort();
I try this method Parsing Nested Objects in a Json using JS without success
Function
var optArray = [], Music, OST, OST details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST details in dataTree[Music][OST]) {
if (OST details in optArray) {
optArray[OST details].push(dataTree[Music][OST][OST details].name)
} else {
optArray[OST details] = [dataTree[Music][OST][OST details].name]
}
}
}
}
You must use nested loops
for Music.children.length
for OST.children.length
for OST details.children.length
Edit : Function
var optArray = [], Music, OST, OST_details;
for (Music in dataTree) {
for (OST in dataTree[Music]) {
for (OST_details in dataTree[Music][OST]) {
if (OST_details in optArray) {
optArray[OST_details].push(dataTree[Music][OST][OST_details].name)
} else {
optArray[OST_details] = [dataTree[Music][OST][OST_details].name]
}
}
}
}
I got it
var dataMusic = document.getElementById('dataMusic').innerHTML;
var dataTree = JSON.parse(dataMusic);
var result = [];
function getAll( input, target ) {
function parseData( input, target ) {
$.each( input, function ( index, obj ) {
if ( index == target ) {
result.push( obj );
}
else {
switch ( $.type( obj ).toLowerCase() ) {
case "object":
case "array":
parseData( obj, target );
break;
}
}
});
}
parseData( dataTree, "name" );
result = result.sort();
return result;
}
alert(JSON.stringify( getAll( dataTree, "name" )));
Thanks to this post :
Parsing multi-level json ; Demo