Jsonata module usage in NodeJS Project - javascript

I have tried jsonata exerciser. It looks cool.
But I have to implement it in my code(NodeJS).
Let's say
Input is:
{
"id": "course_uuid1",
"description": "Sample course description",
"contentType": "COURSE",
"category": "Course",
"durationInSeconds": 500,
"expertiseLevels": ["INTERMEDIATE"],
"imageUrl": "https://percipio.com/courseuuid1/imagelink",
"link": "https://percipio.com/courseuuid1",
"modalities": ["LISTEN", "READ", "WATCH"],
"languageCode": "en",
"parent": null,
"publishDate": "2018-11-19T10:23:34Z",
"sourceName": null,
"technologyTitle": null,
"technologyVersion": null,
"title": "Java",
"by": ["admin"]
}
Transformation logic is:
{
"pkID": id,
"description": description,
"componentTypeID": contentType,
"totalLength": durationInSeconds,
"thumbnailURI": imageUrl,
"locale": languageCode,
"createTimestamp": publishDate,
"title": title,
"lastUpdateUser": by
}
I want output in the transformation logic format, but through NODEJS code.
Please suggest

Install jsonata node module and try below code:
var jsonata = require('jsonata');
let input=
{
"id": "course_uuid1",
"description": "Sample course description",
"contentType": "COURSE",
"category": "Course",
"durationInSeconds": 500,
"expertiseLevels": ["INTERMEDIATE"],
"imageUrl": "https://percipio.com/courseuuid1/imagelink",
"link": "https://percipio.com/courseuuid1",
"modalities": ["LISTEN", "READ", "WATCH"],
"languageCode": "en",
"parent": null,
"publishDate": "2018-11-19T10:23:34Z",
"sourceName": null,
"technologyTitle": null,
"technologyVersion": null,
"title": "Java",
"by": ["admin"]
}
let exp="{'pkID': id,'description': description,'componentTypeID': contentType,'totalLength': durationInSeconds,'thumbnailURI': imageUrl,'locale': languageCode,'createTimestamp': publishDate,'title': title,'lastUpdateUser': by}";
let expression = jsonata(exp);
let expResult = expression.evaluate(input);
console.log(expResult);

I think this is what you want:
var inputJson={
"id": "course_uuid1",
"description": "Sample course description",
"contentType": "COURSE",
"category": "Course",
"durationInSeconds": 500,
"expertiseLevels": ["INTERMEDIATE"],
"imageUrl": "https://percipio.com/courseuuid1/imagelink",
"link": "https://percipio.com/courseuuid1",
"modalities": ["LISTEN", "READ", "WATCH"],
"languageCode": "en",
"parent": null,
"publishDate": "2018-11-19T10:23:34Z",
"sourceName": null,
"technologyTitle": null,
"technologyVersion": null,
"title": "Java",
"by": ["admin"]
};
var outputJson={
"pkID": inputJson.id,
"description": inputJson.description,
"componentTypeID": inputJson.contentType,
"totalLength": inputJson.durationInSeconds,
"thumbnailURI": inputJson.imageUrl,
"locale": inputJson.languageCode,
"createTimestamp": inputJson.publishDate,
"title": inputJson.title,
"lastUpdateUser": inputJson.by
}

Related

Partition messages by date, last read in angular

I want to partition my messages by date for my chat application(Similar to the Microsoft teams app)
The message data will be like
[
{
"id": 577,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "John J"
},
"body": "test test",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T07:59:28.873+00:00"
},
{
"id": 578,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Don V"
},
"body": "ok",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T08:02:26.262+00:00"
},
{
"id": 628,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Sam GP"
},
"body": "Hola",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:27:48.038+00:00"
},
{
"id": 629,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Rawn OP"
},
"body": "ek",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:29:36.705+00:00"
},
{
"id": 630,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Paul John"
},
"body": "hi",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:30:36.695+00:00"
},
{
"id": 631,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Dennise V"
},
"body": "knock knock",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:32:38.035+00:00"
},
{
"id": 632,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Shawn"
},
"body": "who's this",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:25.985+00:00"
},
{
"id": 633,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Pater B"
},
"body": "I see",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:30.783+00:00"
},
{
"id": 634,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Cera LO"
},
"body": "Will call you later",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:38.268+00:00"
},
{
"id": 642,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Rose BH"
},
"body": "hello???????",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-21T05:25:56.642+00:00"
}
]
I need to arrange these data to show the messages by date like
------------------------------Sep 30-----------------------------
Messages sent/received on sep 30
------------------------------Yesterday--------------------------
Messages sent/received on yesterday
------------------------------Last read-------------------------
------------------------------Oct30-----------------------------
------------------------------Yesterday-------------------------
------------------------------Today-----------------------------
For displaying "Sep 30", "yesterday", and "Today" I've created a pipe that converts the timestamp into the month and "yesterday", "today" etc.
I already got the solution to arrange the message by date. But I have to arrange it under the "Last read" block too. Same as by dates. the flag "readStatus" is sed to check whether the message has been read or not" If it is false is should come under "Last read".
Any ideas? Any help will be appreciated.
I imagine you can has something like (if your data is in a variable "data"
dataOrder = {
readed: this.group(this.data.filter((x) => x.readStatus)),
notReaded: this.group(this.data.filter((x) => !x.readStatus)),
};
group(data: any[]) {
return data.reduce((a, b) => {
const dateTime=new Date(b.createdDateTime.substr(0,10)+"T00:00:00.00+00:00")
.getTime()
const element = a.find((x) => x.dateTime == dateTime);
if (!element) a.push({ dateTime:dateTime,data: [b] });
else element.data.push(b);
return a;
}, []);
}
See that "dataOrder" has two properties "readed" and "notReaded", each one are arrays of objects in the way
{
dateTime:a dateTime,
data:an array with the messages
}
This makes easy indicate the date using Angular date pipe, and loop over the messages
So, an .html like
<h1>Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.readed }"
></ng-container>
<h1>Not Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.notReaded }"
></ng-container>
<ng-template #messagedata let-data>
<div *ngFor="let readed of data">
{{ readed.dateTime | date }}
<div *ngFor="let message of readed.data">
{{ message.createdDateTime }} - {{ message.body }}
</div>
</div>
</ng-template>
I use the same template for both type of messages
A stackblitz
Update As the dataOrder it's only change at fisrt is better use a function
getDataOrdered(data:any[])
{
return {
readed: this.group(data.filter((x) => x.readStatus)),
notReaded: this.group(data.filter((x) => !x.readStatus)),
};
}
Then, we can, each time some message change its "readStatus" we can do
this.dataOrder=this.getDataOrdered(this.data)

Drag and drop with express and mongoose

I have a linktree clone project where you can build your portofolio from multiple urls. At the moment, the links are in a chronological order (when they were put in the database). I want to be able to modify their order but don't know what is the best aproach or where to start. The only thing that I could think of was an array stored in Page Schema with the orders of id urls(named pageLayout). I'm a beginner and still learning
The JSON generated is something like this:
{
"theme": "white",
"banner": "uploads/banners/default.png",
"avatar": "uploads/avatars/default.png",
"pageLayout": [],
"_id": "62825469a716308778488106",
"urlName": "test",
"title": "TEST",
"description": "TEST PAGE",
"category": "Photography",
"socialMedia": {
"Instagram": "test",
"Twitter": "test.twitter",
"Tiktok": "test.tiktok"
},
"__v": 0,
"blocks": [
{
"blockType": "links",
"_id": "628a646534a2f89b190bb309",
"title": "Learn Blockchain1",
"user": "628172dff7334877a4ecf19e",
"pageId": "62825469a716308778488106",
"__v": 0,
"links": [
{
"display": true,
"thumbnail": "uploads/linkThumbnails/default.png",
"_id": "628a732533d84c9cf988993b",
"blockId": "628a646534a2f89b190bb309",
"title": "First Project1",
"url": "www.test.com/ethkasbdj",
"user": "628172dff7334877a4ecf19e",
"__v": 0
},{
"display": true,
"thumbnail": "uploads/linkThumbnails/default.png",
"_id": "628a732533d84c9cf988993b",
"blockId": "628a646534a2f89b190bb309",
"title": "First Project2",
"url": "www.test.com/ethkasbdj",
"user": "628172dff7334877a4ecf19e",
"__v": 0
}
],
"id": "628a646534a2f89b190bb309"
}
],
"id": "62825469a716308778488106"

How to deep merge objects in react js

{"activities": [
{
"actor": {
"id": 409,
"avatar": "",
"first_name": "Sakthi",
"last_name": "Vel",
"headline": null,
"is_online": false,
},
"foreign_id": "post.UsPost:253",
"id": "ed50e218-f3e8-11e8-8080-800132d8e9c0",
"object": {
"id": 253,
"comments": 0,
"likes": 0,
"files": [
{
"id": 112,
"file": "",
"content_type": "video/mp4",
"file_type": "video",
"created_at": "2018-11-29T15:10:38.524836Z"
}
],
"post_type": "post",
"is_bookmarked": false,
"is_liked": false,
"link": "/post/api/v1/253/",
"target": "post.UsPost:253",
"foreign_id": "post.UsPost:253",
"actor": {
"id": 409,
"avatar": "",
"first_name": "Sakthi",
"last_name": "Vel",
"headline": null,
"is_online": false,
},
"text": "#Multiple video (.mp4) test. Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.",
"skills": [
"VFX"
],
"created_at": "2018-11-29T15:10:37.426332Z",
"is_link": true,
"view_count": 0,
"created_by": 409
},
"origin": "user:409",
"target": "",
"time": "2018-11-29T15:10:37.426332",
"type": "post",
"verb": "posted"
}
{
"activities": [
{
"actor": {
"id": 64,
"last_name": "",
"headline": "Learning is my Passion",
"is_online": false,
"username": "Uchenna1"
},
"foreign_id": "post.UsPost:183",
"id": "447f6710-eb08-11e8-8080-8001369e78cd",
"object": {
"id": 183,
"comments": 1,
"likes": 1,
"files": [
{
"id": 87,
"content_type": "image/jpg",
"file_type": "image",
"created_at": "2018-11-18T08:02:18.759309Z"
}
],
"post_type": "post",
"is_bookmarked": false,
"is_liked": false,
"link": "/post/api/v1/183/",
"target": "post.UsPost:183",
"foreign_id": "post.UsPost:183",
"actor": {
"id": 64,
"first_name": "Uchenna",
"last_name": "",
"headline": "Learning is my Passion",
"is_online": false,
"username": "Uchenna1"
},
"text": "This is codigo",
"skills": [
"Javascript"
],
"created_at": "2018-11-18T08:02:17.626600Z",
"is_link": true,
"view_count": 10,
"created_by": 64
},
"origin": "user:64",
"target": "",
"time": "2018-11-18T08:02:17.626600",
"type": "post",
"verb": "posted"
}
],
"activity_count": 1,
"actor_count": 1,
"created_at": "2018-11-18T08:02:18.647108",
"group": "posted_2018-11-18",
"id": "451b1eab-eb08-11e8-8080-80007915e2b6.posted_2018-11-18",
"is_read": false,
"is_seen": true,
"updated_at": "2018-11-18T08:02:18.647108",
"verb": "posted"
}
I am facing issue in merging two object. Below is the snap of two object and result.
Here in the above image I wan to merge Old Data and new Data
but after merging getting wrong output i.e new updated data.
I am using command to do it.
let newData = { ...a , ...b }
console.log('new updated data: ',newData)
also I am performing this operation in redux action before dispatching.
Here {"activities": [....],....} is one object and I want to merge with the below one.
Can you clarify do your objects have a child that are objects or arrays and if you mean it's not merging those things or is it not merging anything at all?
for e.g:
let oldData = {
key: value,
key1: { childkey1: value1 }
}
if you have something like this and the problem is like I explained. It's because javascript doesn't do deep merge. it does a shallow merge.
Easiest option would be use a library like lodash that has a function for deep merge.

How to get json data from multiple object levels [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I need to create a table from selected data generated by some rental software in json format via an api. The json data supplied is a list of products, and is quite extensive with objects containing other objects and arrays.
The problem comes when I need to retrieve the data from an object within an object. I want to get Name, weight and Rental Price form the data below. The rental price is in the rental_rate object.
{
"products": [
{
"id": 1404,
"name": "Product 1",
"type": "Product",
"tag_list": [],
"description": "",
"allowed_stock_type": 1,
"allowed_stock_type_name": "Rental",
"stock_method": 1,
"stock_method_name": "Bulk",
"buffer_percent": "50.0",
"post_rent_unavailability": 0,
"replacement_charge": "0.0",
"weight": "0.5",
"barcode": "#st2078",
"active": true,
"accessory_only": false,
"system": false,
"discountable": true,
"rental_rate": {
"item_id": 1404,
"store_id": 1,
"transaction_type": 1,
"rate_definition_id": 3,
"price": "10.0",
"deposit": "0.0",
"category_prices": [],
"properties": {
"day_cost": "0.0",
"day_price": "0.0",
"hour_cost": "0.0",
"hour_price": "0.0",
"__value_types": "---\nday_price: BigDecimal\nhour_price: BigDecimal\ndistance_price: BigDecimal\nflat_rate_price: BigDecimal\nday_cost: BigDecimal\nhour_cost: BigDecimal\ndistance_cost: BigDecimal\nflat_rate_cost: BigDecimal\n",
"distance_cost": "0.0",
"distance_price": "0.0",
"flat_rate_cost": "0.0",
"flat_rate_price": "0.0"
},
"priority": 0,
"date_range": "1900-01-01...3000-01-01"
},
"sale_rate": null,
"product_group_id": 5,
"tax_class_id": 2,
"rental_revenue_group_id": 1,
"sale_revenue_group_id": null,
"created_at": "2017-02-06T00:49:47.755Z",
"updated_at": "2017-02-06T00:49:47.755Z",
"custom_fields": {
"barcode_notes": "Actual Leg Length is: 3'",
"product_serial_number": ""
},
"product_group": {
"id": 5,
"name": "Staging",
"description": "",
"created_at": "2017-02-05T22:20:53.465Z",
"updated_at": "2017-02-05T22:20:53.465Z",
"custom_fields": {}
},
"tax_class": {
"id": 2,
"name": "VAT Standard"
},
"icon": null,
"rental_revenue_group": {
"id": 1,
"name": "Rental",
"description": "",
"active": true
},
"sale_revenue_group": null,
"accessories": [],
"alternative_products": [],
"attachments": [],
"rental_rates": [
{
"id": 1782,
"store_id": null,
"store_name": "",
"rate_definition_id": 3,
"rate_definition_name": "3 Day Week Rate",
"starts_at": null,
"ends_at": null,
"price": "10.0",
"category_prices": []
}
],
"sale_rates": []
},
{
"id": 2395,
"name": "Product 2",
"type": "Product",
"tag_list": [],
"description": "",
"allowed_stock_type": 1,
"allowed_stock_type_name": "Rental",
"stock_method": 2,x
"stock_method_name": "Serialised",
"buffer_percent": "50.0",
"post_rent_unavailability": 0,
"replacement_charge": "0.0",
"weight": "45.0",
"barcode": "",
"active": true,
"accessory_only": false,
"system": false,
"discountable": true,
"rental_rate": {
"item_id": 2395,
"store_id": 1,
"transaction_type": 1,
"rate_definition_id": 3,
"price": "0.0",
"deposit": "0.0",
"category_prices": [],
"properties": {
"day_cost": "0.0",
"day_price": "0.0",
"hour_cost": "0.0",
"hour_price": "0.0",
"__value_types": "---\nday_price: BigDecimal\nhour_price: BigDecimal\ndistance_price: BigDecimal\nflat_rate_price: BigDecimal\nday_cost: BigDecimal\nhour_cost: BigDecimal\ndistance_cost: BigDecimal\nflat_rate_cost: BigDecimal\n",
"distance_cost": "0.0",
"distance_price": "0.0",
"flat_rate_cost": "0.0",
"flat_rate_price": "0.0"
},
"priority": 0,
"date_range": "1900-01-01...3000-01-01"
},
"sale_rate": null,
"product_group_id": 6,
"tax_class_id": 2,
"rental_revenue_group_id": 1,
"sale_revenue_group_id": null,
"created_at": "2017-02-06T00:50:35.834Z",
"updated_at": "2017-02-06T00:50:35.834Z",
"custom_fields": {
"barcode_notes": "",
"product_serial_number": ""
},
"product_group": {
"id": 6,
"name": "Cases",
"description": "",
"created_at": "2017-02-05T22:20:53.509Z",
"updated_at": "2017-02-05T22:20:53.509Z",
"custom_fields": {}
},
"tax_class": {
"id": 2,
"name": "VAT Standard"
},
"icon": null,
"rental_revenue_group": {
"id": 1,
"name": "Rental",
"description": "",
"active": true
},
"sale_revenue_group": null,
"accessories": [],
"alternative_products": [],
"attachments": [],
"rental_rates": [
{
"id": 2773,
"store_id": null,
"store_name": "",
"rate_definition_id": 3,
"rate_definition_name": "3 Day Week Rate",
"starts_at": null,
"ends_at": null,
"price": "0.0",
"category_prices": []
}
],
"sale_rates": []
}
],
"meta": {
"total_row_count": 1376,
"row_count": 2,
"page": 1,
"per_page": 2
}
}
and here is the JS I am using to get the data:
$(document).ready( function() {
$.getJSON( 'https://myapi.com/products', function(data) {
$.each(data.products, function() {
$("table#prod").append("<tr><td>" + this['name'] + "</td><td>" + this['rental_rate.price'] + "</td><td>" + this['weight'] + "kg</td></tr>");
}); }); });
This works fine for name and weight, but not rental price. I have done a thorough search of most places on the internet and not found an answer - my javascript knowledge is limited, which probably means I am going about this all wrong, or not describing it well enough...
Any help or improved methods would be much appreciated!
this.name gets you the name
this.rental_rate gets you the nested rental rate object.
this.rental_rate.price gets you the price.
You can similarly use square bracket notation, but people often only do this when dot syntax won't work (because of spaces in the key).
e.g.
this["name"]
this["rental_rate"]["price"]
this["Invalid Key when accessed via dot syntax but fine with square brackets"]

Retrieve Youtube Tags using Jquery

I'm trying to figure out how to retrieve Youtube Tags and use them in my code behind, but I can't even seem to retrieve any information whatsoever. What would be the best way to retrieve tags with a delimiter like a , or a ; ?
var video_id='VA770wpLX-Q';
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
alert(data.data.tags);
});
This is what the Json object looks like:
{
"apiVersion": "2.1",
"data": {
"id": "VA770wpLX-Q",
"uploaded": "2011-02-24T22:31:02.000Z",
"updated": "2012-04-08T21:37:06.000Z",
"uploader": "drdrevevo",
"category": "Music",
"title": "Dr. Dre - I Need A Doctor (Explicit) ft. Eminem, Skylar Grey",
"description": "Music video by Dr. Dre performing I Need A Doctor featuring Eminem and Skylar Grey (Explicit). © 2011 Aftermath Records",
"tags": ["Dr", "Dre", "Eminem", "New", "Song", "Skylar", "Grey", "GRAMMYs", "Dr.", "Need", "Doctor", "video", "Eazy", "N.W.A.", "NWA", "easy", "drdre", "and", "em"],
"thumbnail": {
"sqDefault": "http://i.ytimg.com/vi/VA770wpLX-Q/default.jpg",
"hqDefault": "http://i.ytimg.com/vi/VA770wpLX-Q/hqdefault.jpg"
},
"player": {
"default": "http://www.youtube.com/watch?v=VA770wpLX-Q&feature=youtube_gdata_player"
},
"content": {
"5": "http://www.youtube.com/v/VA770wpLX-Q?version=3&f=videos&app=youtube_gdata"
},
"duration": 457,
"aspectRatio": "widescreen",
"rating": 4.902695,
"likeCount": "430519",
"ratingCount": 441253,
"viewCount": 88270796,
"favoriteCount": 306556,
"commentCount": 270597,
"status": {
"value": "restricted",
"reason": "requesterRegion"
},
"restrictions": [{
"type": "country",
"relationship": "deny",
"countries": "DE"
}],
"accessControl": {
"comment": "allowed",
"commentVote": "allowed",
"videoRespond": "allowed",
"rate": "allowed",
"embed": "allowed",
"list": "allowed",
"autoPlay": "denied",
"syndicate": "allowed"
}
}
}
Youtube no longer supports "tag" functionality with it's API.

Categories

Resources