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

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]

Related

Looping through nested JSON returns NULL

I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?

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 😊

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.

Get value from complex array

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)

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