Accessing specific JSON values in a deluge script - json

I have a JSON API response that contains multiple entries, with different types of subscriptions and multiple users.
I need to search the list for a "user_name" AND a "subscription", then return any matching "duration". In some cases, there will be more than one "duration" for a user and subscription. I would need the total (sum) of the duration when there is more than one.
For example, here is a part of an example Json I am working with:
[
{
"id": 139387026,
"user_name": "John Smith",
"note": "",
"last_modify": "2022-03-28 14:16:35",
"date": "2022-03-28",
"locked": "0",
"addons_external_id": "",
"description": "",
"info": [
{
"subscription": "basic",
"duration": "22016",
}
]
},
{
"id": 139387027,
"user_name": "John Smith",
"note": "",
"last_modify": "2022-03-28 14:16:35",
"date": "2022-03-28",
"locked": "0",
"addons_external_id": "",
"description": "",
"info": [
{
"subscription": "advanced",
"duration": "10537",
}
]
},
{
"id": 139387028,
"user_name": "Martin Lock",
"note": "",
"last_modify": "2022-03-28 14:16:35",
"date": "2022-03-28",
"locked": "0",
"addons_external_id": "",
"description": "",
"info": [
{
"subscription": "basic",
"duration": "908",
}
]
},
]
So for example, for user_name: "John Smith" and subscription: "advanced", I need to return duration: "10537".
I've used toJsonlist(); to convert it, then used the code below, but it returns all values in the list. I can't figure out how to search for the specific values or add matching entries together.
rows = subscriptions.toJsonlist();
for each row in rows
{
info row;
user_name = row.getJson("user_name");
info "username: " + user_name;
subscription = row.getJson("subscription");
info "subscription: " + subscription;
subscriptionId = row.getJson("subscriptionId");
info "subscription Id: " + subscriptionId;
}
I'm fairly new to programming. Any help is appreciated!

According to your needs , you want to filter your JSON data and get the corresponding value from your filter in user_name and subcription.
Here is the Deluge Script for that. I use clear variable name so that it will not confused you.
//Your Entry Change this based on your filter
input_user_name = "John Smith";
input_subscription = "advanced";
//Your JSON data
json_string_data = '[ { "id": 139387026, "user_name": "John Smith", "note": "", "last_modify": "2022-03-28 14:16:35", "date": "2022-03-28", "locked": "0", "addons_external_id": "", "description": "", "info": [ { "subscription": "basic", "duration": "22016", } ] }, { "id": 139387027, "user_name": "John Smith", "note": "", "last_modify": "2022-03-28 14:16:35", "date": "2022-03-28", "locked": "0", "addons_external_id": "", "description": "", "info": [ { "subscription": "advanced", "duration": "10537", } ] }, { "id": 139387028, "user_name": "Martin Lock", "note": "", "last_modify": "2022-03-28 14:16:35", "date": "2022-03-28", "locked": "0", "addons_external_id": "", "description": "", "info": [ { "subscription": "basic", "duration": "908", } ] } ]';
//Declare the data as JSON
processed_json_data = json_string_data.toJsonlist();
initial_total_duration = 0;//Donot change this
list_of_duration = List();
total_duration_per_username_per_subscription = Map();
for each row in processed_json_data
{
if (row.get("user_name") == input_user_name )
{
info_list = row.get("info").toJSONList();
for each info_row in info_list
{
if (info_row.get("subscription") == input_subscription)
{
info_row_duration = info_row.get("duration").toLong(); // make it integer
list_of_duration.add(info_row_duration);
}
}
}
}
result_map = Map();
//Sum of list_of_duration
for each duration in list_of_duration
{
initial_total_duration = initial_total_duration + duration;
}
result_map.put("user_name",input_user_name);
result_map.put("subscription",input_subscription);
result_map.put("no_of_subscription",list_of_duration.size());
result_map.put("total_duration",initial_total_duration);
info result_map;
And the result should be
{"user_name":"John Smith","subscription":"advanced","no_of_subscription":1,"total_duration":10537}
You can test these script in https://deluge.zoho.com/tryout.
Thanks,
Von

Related

Parsing JSON with VBA-Web and VBA JSON Parser

Need help on parsing JSON data using VBA-Web tool (https://github.com/VBA-tools/VBA-Web) & VBA-JSON Converter
Here is my sample code that I am able to pull the order using the get method but I stumped on parsing the JSON to get the key, value pair that I want
Sub TestWC()
Dim WoocommerceClient As New WebClient
Dim Client As String
Dim Secret As String
WoocommerceClient.BaseUrl = "https://www.example.com"
Client = "ck"
Secret = "cs"
Dim Request As New WebRequest
Request.Method = Httpget
Request.AddQuerystringParam "consumer_key", Client
Request.AddQuerystringParam "consumer_secret", Secret
Dim Response As WebResponse
Request.Resource = "/wp-json/wc/v3/orders"
Set Response = WoocommerceClient.Execute(Request)
//Response.Data -> Should be equal to the JSON data
Dim test As Object
Set test = JsonConverter.ParseJson(Response.Data)
End Sub
When I run this code it will have a error popup saying object required 424 . I also did another work around where I put into the first cell the whole JSON Data using Sheet1.Range("A1").Value = Response.Content then by pulling the data from the cell into the function
Set test = JsonConverter.ParseJson(Sheet1.Range("A1").Value)
I still get the object required error, here is a Sample JSON format from Woocommerce REST API
"id": 727,
"parent_id": 0,
"number": "727",
"order_key": "wc_order_58d2d042d1d",
"created_via": "rest-api",
"version": "3.0.0",
"status": "processing",
"currency": "USD",
"date_created": "2017-03-22T16:28:02",
"date_created_gmt": "2017-03-22T19:28:02",
"date_modified": "2017-03-22T16:28:08",
"date_modified_gmt": "2017-03-22T19:28:08",
"discount_total": "0.00",
"discount_tax": "0.00",
"shipping_total": "10.00",
"shipping_tax": "0.00",
"cart_tax": "1.35",
"total": "29.35",
"total_tax": "1.35",
"prices_include_tax": false,
"customer_id": 0,
"customer_ip_address": "",
"customer_user_agent": "",
"customer_note": "",
"billing": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "969 Market",
"address_2": "",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US",
"email": "john.doe#example.com",
"phone": "(555) 555-5555"
},
"shipping": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "969 Market",
"address_2": "",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US"
},
"payment_method": "bacs",
"payment_method_title": "Direct Bank Transfer",
"transaction_id": "",
"date_paid": "2017-03-22T16:28:08",
"date_paid_gmt": "2017-03-22T19:28:08",
"date_completed": null,
"date_completed_gmt": null,
"cart_hash": "",
"meta_data": [
{
"id": 13106,
"key": "_download_permissions_granted",
"value": "yes"
}
],
"line_items": [
{
"id": 315,
"name": "Woo Single #1",
"product_id": 93,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "6.00",
"subtotal_tax": "0.45",
"total": "6.00",
"total_tax": "0.45",
"taxes": [
{
"id": 75,
"total": "0.45",
"subtotal": "0.45"
}
],
"meta_data": [],
"sku": "",
"price": 3
},
{
"id": 316,
"name": "Ship Your Idea – Color: Black, Size: M Test",
"product_id": 22,
"variation_id": 23,
"quantity": 1,
"tax_class": "",
"subtotal": "12.00",
"subtotal_tax": "0.90",
"total": "12.00",
"total_tax": "0.90",
"taxes": [
{
"id": 75,
"total": "0.9",
"subtotal": "0.9"
}
],
"meta_data": [
{
"id": 2095,
"key": "pa_color",
"value": "black"
},
{
"id": 2096,
"key": "size",
"value": "M Test"
}
],
"sku": "Bar3",
"price": 12
}
],
"tax_lines": [
{
"id": 318,
"rate_code": "US-CA-STATE TAX",
"rate_id": 75,
"label": "State Tax",
"compound": false,
"tax_total": "1.35",
"shipping_tax_total": "0.00",
"meta_data": []
}
],
"shipping_lines": [
{
"id": 317,
"method_title": "Flat Rate",
"method_id": "flat_rate",
"total": "10.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": []
}
],
"fee_lines": [],
"coupon_lines": [],
"refunds": [],
"_links": {
"self": [
{
"href": "https://example.com/wp-json/wc/v3/orders/727"
}
],
"collection": [
{
"href": "https://example.com/wp-json/wc/v3/orders"
}
]
}
}```

How can I PUT data into nested JSON in Angular?

I have this JSON file.
{mood: [ {
"id":"1",
"text": "Annoyed",
"cols": 1,
"rows": 2,
"color": "lightgreen",
"route":"/angry",
"musics": [
{
"id": "0",
"name": "English- Heaven's Peace",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EgleopO8DiEdsNKgqYZZSEKF",
"descpription": "Tunes that soothe your pained soul",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "1",
"name": "English- Hell's Fire",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EgmZitRQf1X1iYwWW_nUF44L",
"descpription": "Beats that match the ones of your heart",
"reviews": [
{
"name": "abc",
"rating": 3.5,
"review": "energetic",
"date": ""
}
]
},
{
"id": "2",
"name": "Hindi",
"image": "images/music.png",
"link": "",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "3",
"name": "Punjabi",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3Egnntch2thUO55YqPQgo4Qh7",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "4",
"name": "Mix and Match",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EglN5LVTETqH3ipRLfXmY6MB",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 5,
"review": "energetic",
"date": ""
}
]
}
]
}]
}`
I have created a service that should update any changes in the moods section.
putMood(mood: Mood): Observable<Mood> {
const httpOptions ={
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.put<Mood>(baseURL + 'moods/' + mood.id, mood, httpOptions)
.pipe(catchError(this.processHTTPMsgService.handleError));
}
And a submit function that should put my newly entered review in the reviews section of my json file under musics section.
onSubmit(){
this.review = this.reviewForm.value;
this.review.date = new Date().toISOString();
this.music.reviews.push(this.review);
this.moodservice.putMood(this.mood)
.subscribe(mood => {
this.mood=mood;
},
errmess => {this.mood = null; this.errMess = <any>errmess;});
}
Using this service and function my review is not uploaded to JSON file. What am I doing wrong?

Structure data inside a Document database

I'm building a app that is going to serve as an agenda or a scheduling book for some services. It's planned to the app to work in a "per customer" way, Angular in the front-end and to use the new Google Firestore, for all the real time and pseudo-backendless stuff.
The question is, as I have never worked with NoSQL databases before, how should I structure the data inside Firestore?
I thought about something that would look like this:
{
//Collection
"customer-a": {
//Document
"info": {
"name": "Customer A",
"Phones": [{
"contact-name": "",
"number": ""
}],
"address": {
"type": "street",
"name": "",
"number": 0,
"neighborhood": "",
"city": "",
"state": "",
"zipcode": "",
"country": "",
"coordinates": {
"latitude": "",
"longitude": ""
}
}
},
//Document
"config": {
"active-theme": "",
"themes": [{}]
},
//Document
"customer-data": {
//SubCollection
"employees": {
//Document
"employee-a": {
"name": "",
"phone": "",
"rattings": [],
"address": {
"type": "street",
"name": "",
"number": 0,
"neighborhood": "",
"city": "",
"state": "",
"zipcode": "",
"country": ""
},
//SubCollection
"schedulings": {
//Document
"2017": {
"total": 300,
"scheduling": [{
"client": {
"name": "",
"phone": "",
"rating": 5,
},
"price": 10,
"services": [{
"name": "",
"price": 10
}],
"datetime": "",
}]
},
"2018": {
"total": 300,
"scheduling": [{
"client": {
"name": "",
"phone": "",
"classificacao": 5,
},
"price": 10,
"services": [{
"name": "",
"price": 10
}],
"datetime": "",
}]
},
}
}
},
//SubCollection
"stock": {}
}
}
}
I'm thinking on splitting the scheduling into years because I think it may grow in size a lot, but as I said, I've never worked with this kind of database, so I don't really know how much data I could nest inside a document, for example...
As an exaggerated amount of data for a base calculation I thought about around 200k "objects" that would be stored for each employee per year, is that much or it's ok to store that much data nested?
Should I keep creating sub collections inside Firestore or it should be one single collections to store only different documents and nest everything?
Hope someone can help me,
Thanks.

Convert JSON to GridView in VB.NET

I have the following JSON that I am looking to convert into a GridView. I have been able to successfully do this for a portion of the JSON. It seems to fail on the deposit and withdrawals section. Anyone have any suggestions?
{
"results": [
{
"id": "51142254",
"tp_id": "!XP4D49X0CD123628",
"firstname": "Owner",
"lastname": "Operator",
"email": "",
"phone": "",
"enrolled": "1",
"balance": 247.54,
"fleet": "Test Express",
"deposits": [
{
"id": "184022380",
"date": "2016-02-17",
"amount": "200.00",
"transID": "135246",
"memo": "Scheduled Deposit",
"status": "Cleared"
},
{
"id": "184022383",
"date": "2016-02-25",
"amount": "200.00",
"transID": "246357",
"memo": "Scheduled Deposit",
"status": "Cleared"
},
{
"id": "184022386",
"date": "2016-03-02",
"amount": "200.00",
"transID": "975468",
"memo": "Scheduled Deposit",
"status": "Cleared"
}
],
"withdrawals": [
{
"id": "184026949",
"date": "2016-03-09",
"amount": "352.46",
"transID": "395920",
"memo": "Invoice\r\n\r\n100234",
"status": "Cleared"
}
]
},
{
"id": "51142326",
"tp_id": "!XP4D49X7CD123612",
"firstname": "Owner",
"lastname": "Operator",
"email": "",
"phone": "",
"enrolled": "1",
"balance": 0,
"fleet": "Test\r\nExpress",
"deposits": [],
"withdrawals": []
}
]
}
This is the current code I use for GridView.
Dim UserList As List(Of api_Test_Deposit) = JsonConvert.DeserializeObject(Of List(Of api_Test_Deposit))(GetUrlString(searchType, searchValue))
Dim table = JsonConvert.DeserializeObject(Of DataTable)(GetUrlString(searchType, searchValue))
Return table

jquery object as parameter to function

This is my jquery response:
[
{ "depot":
{
"id": "D1",
"intersection": {
"first": "Markham",
"second": "Lawrence"
},
"address": {
"number": "25",
"street": "Cougar Court",
"city": "Scarborough",
"province": "ON",
"postal_code": "M1J"
}
},
"vehicle": [
{
"id": "V1",
"depot_id": "D1",
"model": "Ford Focus",
"price": "45",
"km_per_litre": "15",
"cargo_cu_m": "YES",
"category": "Compact car",
"image": "www.coolcarz.com"
}
,
{
"id": "V2",
"depot_id": "D1",
"model": "Honda Civic",
"price": "45",
"km_per_litre": "150",
"cargo_cu_m": "YES",
"category": "Compact car",
"image": "www.coolcarz.com"
}
,
{
"id": "V8",
"depot_id": "D1",
"model": "Pontiac Aztek",
"price": "10",
"km_per_litre": "6",
"cargo_cu_m": "YES",
"category": "SUV",
"image": "www.nocoolcarz.com"
}
,
{
"id": "V12",
"depot_id": "D1",
"model": "Chevrolet Impala",
"price": "45",
"km_per_litre": "12",
"cargo_cu_m": "YES",
"category": "Standard car",
"image": "www.coolcarz.com"
}
,
{
"id": "V29",
"depot_id": "D1",
"model": "Nissan Leaf",
"price": "150",
"km_per_litre": "0",
"cargo_cu_m": "YES",
"category": "Electronic Car",
"image": "www.coolcarz.com"
}
]
}
,
{ "depot":
{
"id": "A1",
"intersection": {
"first": "Markham",
"second": "Lawrence"
},
"address": {
"number": "25",
"street": "Cougar Court",
"city": "Scarborough",
"province": "ON",
"postal_code": "m1J"
}
},
"vehicle": [
]
}
]
What I want to do is that at some point in my code, when I have received this response data, I want to pass , say data[0] or or data[0].vehicle[1] to a function
The way I am doing it now is:
function(data) {
var items = [];
for( i=0; i<data.length; i++){
items.push('<b>' + data[i].depot.intersection.first+"-"+ data[i].depot.intersection.second + " depot has following cars:"+ '</b>');
for( k=0; k<data[i].vehicle.length;k++){
str = '<li> ' + data[i].vehicle[k].category +", $"+ data[i].vehicle[k].price +' a day </li>';
items.push(str);
in effect I am trying to create a hyperlink (with vehicle category as text), and when user clicks on this hyperlink, I want to pass on the vehicle information array to a new function called moreInfo that does its job. Rit now when I do this and click the hyperlink, I see the error
missing ] after element list
timepass([object Object],[object Object]
Any ideas?
Remove 2 square brackets from beginning and end of your json code and use use it as an object not as an array.
What you did was creating an array of objects not JSON object