jquery object as parameter to function - json

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

Related

Accessing specific JSON values in a deluge script

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

Moving a JSON array which have another array elements to the same LEVEL

I have the following JSON which have an element array_within_array in another array. So I want to pull both array_within_array element and upper array element(event_array) to root level using jq.
So here there are 3 events.
meal_selection
login
placed_order
Event placed_order have two sub-events in array. So after conversion there should be 4 events(1 from meal_selection, 1 from login and 2 from placed_order). these all should be on the same level.
Here is the JSON
{
"region": "USA",
"user_id": "123",
"event_array": [{
"event_attributes": {
"date": "2021-08-17",
"category": "lunch",
"location": "office"
},
"event_name": "meal_selection",
"created_at": "2021-08-13 01:28:57"
},
{
"event_name": "login",
"created_at": "2021-08-13 01:29:02"
},
{
"event_attributes": {
"array_within_array": [
{
"date": "2021-08-17",
"category": "lunch",
"location": "office"
},
{
"date": "2021-08-18",
"category": "dinner",
"location": "home"
}
]
},
"event_name": "placed_order",
"created_at": "2021-08-13 01:28:08"
}
]
}
and I want to convert to the below one
{
"region": "USA",
"user_id": "123",
"event_attributes": {
"date": "2021-08-17",
"category": "lunch",
"location": "office"
},
"event_name": "meal_selection",
"created_at": "2021-08-13 01:28:57"
}
{
"region": "USA",
"user_id": "123",
"event_name": "login",
"created_at": "2021-08-13 01:29:02"
}
{
"region": "USA",
"user_id": "123",
"event_attributes": {
"date": "2021-08-17",
"category": "lunch",
"location": "office"
},
"event_name": "placed_order",
"created_at": "2021-08-13 01:28:08"
}
{
"region": "USA",
"user_id": "123",
"event_attributes": {
"date": "2021-08-18",
"category": "dinner",
"location": "home"
},
"event_name": "placed_order",
"created_at": "2021-08-13 01:28:08"
}
Here's a straightforward solution that keeps things simple by using two steps:
{ region, user_id} + (.event_array[] )
| if .event_attributes|has("array_within_array")
then .event_attributes.array_within_array as $a
| .event_attributes = $a[]
else .
end

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?

Convert nested json to csv to sheets json api

I'm want to make my json to csv so that i can upload it on google sheets and make it as json api. Whenever i have change data i will just change it on google sheets. But I'm having problems on converting my json file to csv because it changes the variables whenever i convert it. I'm using https://toolslick.com/csv-to-json-converter to convert my json file to csv.
What is the best way to convert json nested to csv ?
JSON
{
"options": [
{
"id": "1",
"value": "Jumbo",
"shortcut": "J",
"textColor": "#FFFFFF",
"backgroundColor": "#00000"
},
{
"id": "2",
"value": "Hot",
"shortcut": "D",
"textColor": "#FFFFFF",
"backgroundColor": "#FFFFFF"
}
],
"categories": [
{
"id": "1",
"order": 1,
"name": "First Category",
"active": true
},
{
"id": "2",
"order": 2,
"name": "Second Category",
"shortcut": "MT",
"active": true
}
],
"products": [
{
"id": "03c6787c-fc2a-4aa8-93a3-5e0f0f98cfb2",
"categoryId": "1",
"name": "First Product",
"shortcut": "First",
"options": [
{
"optionId": "1",
"price": 23
},
{
"optionId": "2",
"price": 45
}
],
"active": true
},
{
"id": "e8669cea-4c9c-431c-84ba-0b014f0f9bc2",
"categoryId": "2",
"name": "Second Product",
"shortcut": "Second",
"options": [
{
"optionId": "1",
"price": 11
},
{
"optionId": "2",
"price": 20
}
],
"active": true
}
],
"discounts": [
{
"id": "1",
"name": "S",
"type": 1,
"amount": 20,
"active": true
},
{
"id": "2",
"name": "P",
"type": 1,
"amount": 20,
"active": true
},
{
"id": "3",
"name": "G",
"type": 2,
"amount": 5,
"active": true
}
]
}
Using python, this can be easily done or almost done. Maybe this code will help you in some way to understand that.
import json,csv
data = []
with open('your_json_file_here.json') as file:
for line in file:
data.append(json.loads(line))
length = len(data)
with open('create_new_file.csv','w') as f:
writer = csv.writer(f)
writers = csv.DictWriter(f, fieldnames=['header1','header2'])
writers.writeheader()
for iter in range(length):
writer.writerow((data[iter]['specific_col_name1'],data[iter]['specific_col_name2']))
f.close()

Problem retrieving data from json output

I am a noob when it comes to json. The more I use it, I am starting to like it. I have a output that looks like this
[
{
"product": {
"id": "6",
"category": "Books",
"created": "2010-04-13 15:15:18",
},
"availability": [
{
"country": "United Kingdom",
"price": "$13.99",
},
{
"country": "Germany",
"price": "$13.99",
}
]
}
]
Actually I have listed only one product, But output has many products listed. I want to loop through this json output and get all the product's category, countries where they are available and price using fbjs.
I appreciate any help.
Thanks.
If your JSON is like this,
var products = [
{
"product": {
"id": "6",
"category": "Books",
"created": "2010-04-13 15:15:18",
},
"availability": [
{
"country": "United Kingdom",
"price": "$13.99",
},
{
"country": "Germany",
"price": "$13.99",
}
]
},
{
"product": {
"id": "7",
"category": "Books",
"created": "2010-04-13 15:15:18",
},
"availability": [
{
"country": "United Kingdom",
"price": "$13.99",
},
{
"country": "Germany",
"price": "$13.99",
}
]
}
]
You can iterate through:
for(var index = 0; index < products.length; index++) {
alert(products[index].product.category);
}