Get value from complex array - javascript

Hi I have an array (see below for the first part of the array) and I can get the name using the code (my code is in a loop to get all names from the array)
jsonFabric.values[i].name
which gives me "3002-023"
How do I get the labels name?
which would give me "Fabric".
I have tried many variations including
jsonFabric.values[i].labels['name']
but they do not get "Fabric"
{
"totalRows": 151,
"values": [
{
"width": 1338,
"height": 2397,
"isNew": true,
"defaultScene": null,
"displayUrl": "https://example.com/designs-324/3002%20023_small.png?1=1&width=500&Cache=Default&height=500&p.dc=1&mode=max&format=jpg&timestamp=636244299470877669",
"renderUrl": "https://example.com/designs-324/3002%20023.tif?1=1&width=-1&Cache=Default&p.dc=1&mode=max&format=jpg&timestamp=636244299470877669",
"designOptions": {
"repeat": true,
"width": 114,
"height": 203,
"gloss": 0,
"contrast": 0,
"dropX": 0,
"dropY": 0,
"placingPointX": 0.5,
"placingPointY": 0.5,
"flip": false,
"rotation": 0
},
"id": 324,
"name": "3002-023",
"properties": [],
"propertiesPerLabel": [],
"labels": [
{
"id": 1,
"parentId": 0,
"name": "Fabric",
"path": []
}
],
"description": null,
"createDate": "2017-03-06T20:45:47.0877669",
"lastSaveDate": "2017-03-09T13:49:38.5256163",
"attachments": [],
"storageName": "3002 023.tif",
"storagePath": "designs-324/3002 023.tif",
"relations": {
"direct": []
},
"referenceId": "3002-023.tif"
},
and so on.....
{
"width": 1354,
"height": 1870,
"isNew": true,

labels represents an array. You need to access the first object of this array to print its name:
jsonFabric.values[i].labels[0].name

labels is an array, so you need to either select the first element(if there is only one) or loop through to grab the name from each.
let obj = {
"totalRows": 151,
"values": [{
"width": 1338,
"height": 2397,
"isNew": true,
"defaultScene": null,
"displayUrl": "https://example.com/designs-324/3002%20023_small.png?1=1&width=500&Cache=Default&height=500&p.dc=1&mode=max&format=jpg&timestamp=636244299470877669",
"renderUrl": "https://example.com/designs-324/3002%20023.tif?1=1&width=-1&Cache=Default&p.dc=1&mode=max&format=jpg&timestamp=636244299470877669",
"designOptions": {
"repeat": true,
"width": 114,
"height": 203,
"gloss": 0,
"contrast": 0,
"dropX": 0,
"dropY": 0,
"placingPointX": 0.5,
"placingPointY": 0.5,
"flip": false,
"rotation": 0
},
"id": 324,
"name": "3002-023",
"properties": [],
"propertiesPerLabel": [],
"labels": [{
"id": 1,
"parentId": 0,
"name": "Fabric",
"path": []
}],
"description": null,
"createDate": "2017-03-06T20:45:47.0877669",
"lastSaveDate": "2017-03-09T13:49:38.5256163",
"attachments": [],
"storageName": "3002 023.tif",
"storagePath": "designs-324/3002 023.tif",
"relations": {
"direct": []
},
"referenceId": "3002-023.tif"
}]
}
console.log(obj.values[0].labels[0].name)

Related

SQL Server update JSON with url in a property without introducing escaping sequences

I am trying to update an array in a JSON contained into a column inside my DB, it's not clear to me what i did wrong but seems like that when a JSON property (a string) contain backslash, those value will be escaped.
I don't want that escaping is introduced into DB data, is there a way to prevent this or the only option is to proceed with a REPLACE() at the end of JSON modification?
Here the query :
SELECT TOP 1 JSON_MODIFY(
CASE WHEN ISNULL([_DOCUMENTS],'') = '' THEN '{}' ELSE [_DOCUMENTS] END ,
'$.Documents',
JSON_QUERY(
(
SELECT *
FROM OPENJSON([_DOCUMENTS], '$.Documents') WITH (
Title nvarchar(1000) '$.Title',
Category nvarchar(1000) '$.Category',
NumberOfPages INT '$.NumberOfPages',
SizeInBytes INT '$.SizeInBytes',
MimeType nvarchar(1000) '$.MimeType',
[Date] nvarchar(1000) '$.Date',
ResourceId INT '$.ResourceId',
ResourceType INT '$.ResourceType',
ParentEntityType INT '$.ParentEntityType',
[Url] nvarchar(1000) '$.Url',
[Site] nvarchar(1000) '$.Site',
[Description] nvarchar(1000) '$.Description',
PreviewImageUrl nvarchar(1000) '$.PreviewImageUrl',
LanguageCode nvarchar(1000) '$.LanguageCode',
Sort INT '$.Sort'
)
WHERE LanguageCode != N'ru'
FOR JSON PATH
)
)
)
FROM [dbo].[myTalbe]
Here the JSON before transformation :
{
"ResourceId": 0,
"ResourceType": 999,
"ParentEntityId": 3,
"ParentEntityType": 60,
"Links": [],
"ProvisionalMainImage": {
"MimeType": "image/png",
"ImageKind": 0,
"Size": 0,
"Annotation": null,
"ImageGroup": "default",
"ResourceId": 0,
"ResourceType": 60,
"ParentEntityId": 0,
"ParentEntityType": 0,
"Url": "",
"Site": "",
"Description": "",
"PreviewImageUrl": "",
"LanguageCode": "template",
"Sort": 0
},
"Images": [],
"YouTubeVideos": [],
"Documents": [{
"Title": "",
"Category": "",
"Author": "",
"NumberOfPages": 0,
"SizeInBytes": 161356,
"MimeType": "application/pdf",
"Date": "2000-01-01T00:00:00",
"ResourceId": 0,
"ResourceType": 70,
"ParentEntityId": 0,
"ParentEntityType": 0,
"Url": "https://mySite/..",
"Site": "",
"Description": "",
"PreviewImageUrl": "https://mySite/..",
"LanguageCode": "pt",
"Sort": 0
}, {
"Title": "",
"Category": "",
"Author": "",
"NumberOfPages": 0,
"SizeInBytes": 192958,
"MimeType": "application/pdf",
"Date": "2000-01-01T00:00:00",
"ResourceId": 0,
"ResourceType": 70,
"ParentEntityId": 0,
"ParentEntityType": 0,
"Url": "https://mySite/..",
"Site": "",
"Description": "",
"PreviewImageUrl": "https://mySite/..",
"LanguageCode": "ru",
"Sort": 0
}, {
"Title": "",
"Category": "",
"Author": "",
"NumberOfPages": 0,
"SizeInBytes": 162314,
"MimeType": "application/pdf",
"Date": "2000-01-01T00:00:00",
"ResourceId": 0,
"ResourceType": 70,
"ParentEntityId": 0,
"ParentEntityType": 0,
"Url": "https://mySite/..",
"Site": "",
"Description": "",
"PreviewImageUrl": "https://mySite/..",
"LanguageCode": "template",
"Sort": 0
}
],
"Htmls": []
}
Here the result after the query do its transofrmation :
{
"ResourceId": 0,
"ResourceType": 999,
"ParentEntityId": 3,
"ParentEntityType": 60,
"Links": [],
"ProvisionalMainImage": {
"MimeType": "image/png",
"ImageKind": 0,
"Size": 0,
"Annotation": null,
"ImageGroup": "default",
"ResourceId": 0,
"ResourceType": 60,
"ParentEntityId": 0,
"ParentEntityType": 0,
"Url": "",
"Site": "",
"Description": "",
"PreviewImageUrl": "",
"LanguageCode": "template",
"Sort": 0
},
"Images": [],
"YouTubeVideos": [],
"Documents": [{
"Title": "",
"Category": "",
"NumberOfPages": 0,
"SizeInBytes": 161356,
"MimeType": "application\/pdf",
"Date": "2000-01-01T00:00:00",
"ResourceId": 0,
"ResourceType": 70,
"ParentEntityType": 0,
"Url": "https:\/\/mySite\/..",
"Site": "",
"Description": "",
"PreviewImageUrl": "https:\/\/mySite\/..",
"LanguageCode": "pt",
"Sort": 0
}, {
"Title": "",
"Category": "",
"NumberOfPages": 0,
"SizeInBytes": 162314,
"MimeType": "application\/pdf",
"Date": "2000-01-01T00:00:00",
"ResourceId": 0,
"ResourceType": 70,
"ParentEntityType": 0,
"Url": "https:\/\/mySite\/..",
"Site": "",
"Description": "",
"PreviewImageUrl": "https:\/\/mySite\/..",
"LanguageCode": "template",
"Sort": 0
}
],
"Htmls": []
}
As you can see the wrong '\ /' sequence is introduced at some point by the function used (one of them probably do the escaping thing). I can easily revert '\ /' back to '/' with just a REPLACE operation. But that approach seems risky to me, if there are other escaping i didn't see in my testing.
I prefer to understand how to use the function above, to manupulate JSON without introducing escaping artifacts.
If I understand the question correctly, you are trying to delete items from the $.Documents JSON array, based on a specific condition. The documentation explains, that ... If the source data contains special characters, the FOR JSON clause escapes them in the JSON output with '\' ..., so a possible approach is to parse this JSON array with OPENJSON() and default schema, and rebuild it again using string aggregation:
SELECT JSON_MODIFY(
[_DOCUMENTS],
'$.Documents',
JSON_QUERY((
SELECT CONCAT('[', STRING_AGG([value], ','), ']')
FROM OPENJSON([_DOCUMENTS], '$.Documents')
WHERE JSON_VALUE([value], '$.LanguageCode') != 'ru'
))
)
FROM [dbo].[myTalbe]

JSON not indexing correctly

I have this JSON:
[
{
"type": "GUILD_TEXT",
"deleted": false,
"guild": "898666651547996200",
"guildId": "898666651547996200",
"parentId": "903388176100495390",
"permissionOverwrites": [
"900991433576689675",
"917426278003523604",
"898666651547996200",
"898825198709641246"
],
"messages": [
"928781911982219307"
],
"threads": [],
"nsfw": false,
"id": "903388255528042566",
"name": "updates",
"rawPosition": 41,
"topic": null,
"lastMessageId": "928781911982219307",
"rateLimitPerUser": 0,
"createdTimestamp": 1635454944260
}
]
(call = the json)
Shouldn't this be returning "updates": call[0]["name"]
Via JS, it is returning undefined.
call[0] is returning as {
I've tried it on various other languages and it has been working as intended... just not in JS.
It does work:
const call = [{
"type": "GUILD_TEXT",
"deleted": false,
"guild": "898666651547996200",
"guildId": "898666651547996200",
"parentId": "903388176100495390",
"permissionOverwrites": [
"900991433576689675",
"917426278003523604",
"898666651547996200",
"898825198709641246"
],
"messages": [
"928781911982219307"
],
"threads": [],
"nsfw": false,
"id": "903388255528042566",
"name": "updates",
"rawPosition": 41,
"topic": null,
"lastMessageId": "928781911982219307",
"rateLimitPerUser": 0,
"createdTimestamp": 1635454944260
}]
console.log(call[0]["name"]) // updates
const callString = JSON.stringify(call)
console.log(JSON.parse(callString)[0]["name"]) // updates
I tried
var name= call[0].name;
and
var name= call[0]["name"];
evertything is working properly returning "updates".

Loop through JSON response and return values that matches another JSON response into a new key value

I have the following API call returned values that has an id value
var sites =
{
"response": [
{
"id": 1433,
"name": "Bronx 1",
"address": "5288 McGlynn Hills",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1433/attributes"
},
{
"id": 1434,
"name": "Bronx 2",
"address": "126 Mann Divide",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1434/attributes"
}
]
}
I need to use the ID value from the call above an compare it to the following API response site_id value
var floors =
{
"response": [
{
"id": 118,
"label": "Crowded floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 100,
"site_common_area": 50,
"floor_common_area": 50,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=118",
"site_id": 1433,
"icon_scale_factor": 0.2,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/118/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/118/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1390"
]
},
{
"id": 119,
"label": "Normal floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 200,
"site_common_area": 0,
"floor_common_area": 200,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=119",
"site_id": 1453,
"icon_scale_factor": 0.7,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/119/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/119/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1391"
]
}
],
"count": 2
}
When site.id = floors.site_id I want to build a new key value pair that looks like this: only for the matched values
var match {floor.id: site.name}
I am having trouble looping over both and returning values any help is appreciated
Thanks
Hey #Abdullah Albyati,
I try to created what u asked but, it's actually not that usefull but here it is:
var floors =
{
"response": [
{
"id": 118,
"label": "Crowded floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 100,
"site_common_area": 50,
"floor_common_area": 50,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=118",
"site_id": 1452,
"icon_scale_factor": 0.2,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/118/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/118/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1390"
]
},
{
"id": 119,
"label": "Normal floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 200,
"site_common_area": 0,
"floor_common_area": 200,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=119",
"site_id": 1453,
"icon_scale_factor": 0.7,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/119/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/119/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1391"
]
}
],
"count": 2
};
var sites =
{
"response": [
{
"id": 1433,
"name": "Bronx 1",
"address": "5288 McGlynn Hills",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1433/attributes"
},
{
// "id": 1434,
"id": 1453,
"name": "Bronx 2",
"address": "126 Mann Divide",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1434/attributes"
}
]
}
var conbined = floors.response.reduce((obj, floor) => {
var site_id = floor.site_id;
var site = sites.response.find(site => site.id === site_id);
if(site) {
console.log(site.name);
return { ...obj, floor_site_id: site.name }
}
return obj;
}, {});
console.log(conbined);
In the data you gave there was no data to combine so i changed one of the id's. Hope this works for you 😊

Javascript Array remove element when price is lower than X

I want to delete items from my array where the price is lower than 20
This is my array:
[
{
"suggested_price": 50,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 50,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
}
]
and if the suggested_price is lower than 20, i will delete that out of my array list
I tried to find how on the internet but couldn't find how :/
Only find sorting array by price
You want to use filter.
const items = [{
suggested_price: 19,
suggested_price_floor: 0,
name: 'Itemname',
image: 'link',
wear: null,
color: 'ffbb00',
id: 6039365
},
{
suggested_price: 50,
suggested_price_floor: 0,
name: 'Itemname',
image: 'link',
wear: null,
color: 'ffbb00',
id: 6039365
}
];
const reducedItems = items.filter(item => (item.suggested_price > 20));
console.log(reducedItems)
;
you can use array.filter, which will create a new array with the condition passed on the filter function
var res = [
{
"suggested_price": 50,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 6,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 15,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
},
{
"suggested_price": 34,
"suggested_price_floor": 0,
"name": "Itemname",
"image": "link",
"wear": null,
"color": "ffbb00",
"id": 6039365
}
]
// instead of 30 you can replace with your value
let filteredArray = res.filter(o => o.suggested_price > 30)
console.log("filtered Array greater than 30", filteredArray)
// addition if you want to reduce the array , you can do the below
let totalOfSuggPrice = filteredArray.reduce((a,c) => ({total: a.suggested_price + c.suggested_price}))
console.log("sum of the filtered array - total of the suggested price",totalOfSuggPrice )

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"]

Categories

Resources