Very Complex Json with same field name - flutter

My colleague is response for backend development, this is one of example of the API response.
I want to know that how can I separate it to the map?
And There have same name, I am very difficult to handle it. JSON to Dart generated code also will have error case by same name.
Is there have any other solution to handle this Json?
{
"formId": 1,
"formTypeId": 2,
"formTemplateId": 1,
"version": 1,
"history": "N",
"refNum": "AGQ/T01/01/A1/QA2/0001",
"dateOfAcceptance": "2020/12/16 14:54:01",
"dateOfReacceptance": "2020/12/16 14:54:01",
"blockId": 242,
"floorId": 1,
"flatId": 98,
"isPublic": "N",
"locationId": 1,
"fromFloorId": 1,
"toFloorId": 2,
"elevationId": 1,
"isNextVendor": "Y",
"isMultipleVendor": "N",
"formStatusId": 1,
"checkResults": 1,
"submissionDate": "2020/12/16 14:54:01",
"submittedBy": "ADMINISTRATOR",
"siteId": "YLTL",
"formDetails": [
{
"formDetailsId": 1,
"formId": 1,
"title": "A. 驗收項目",
"checkType": 1,
"required": "Y",
"parentId": 0,
"orderNum": 1,
"formDetailsOptions": [],
"fromDetails": [
{
"formDetailsId": 3,
"formId": 1,
"title": "Title group",
"checkType": 2,
"required": "Y",
"parentId": 1,
"orderNum": 1,
"formDetailsOptions": [],
"fromDetails": [
{
"formDetailsId": 4,
"formId": 1,
"title": "門編號:",
"checkType": 5,
"required": "Y",
"parentId": 3,
"orderNum": 1,
"answerVal": "A001",
"formDetailsOptions": []
},
{
"formDetailsId": 5,
"formId": 1,
"title": "位置:",
"checkType": 6,
"required": "Y",
"parentId": 3,
"orderNum": 2,
"formDetailsOptions": [
{
"formDetailsOptionsId": 1,
"formDetailsId": 5,
"orderNum": 1,
"optionDesc": "單位大門",
"defectOpts": "N",
"additionOpts": "N",
"selected": "N"
},
{
"formDetailsOptionsId": 2,
"formDetailsId": 5,
"orderNum": 2,
"optionDesc": "廚房門",
"defectOpts": "N",
"additionOpts": "N",
"selected": "N"
},
{
"formDetailsOptionsId": 3,
"formDetailsId": 5,
"orderNum": 3,
"optionDesc": "廁所客廳",
"defectOpts": "N",
"additionOpts": "N",
"selected": "N"
}
]
},
{
"formDetailsId": 6,
"formId": 1,
"title": "假框抆塞:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 3,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 7,
"formId": 1,
"title": "門框尺寸:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 4,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 8,
"formId": 1,
"title": "門框木料:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 5,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 9,
"formId": 1,
"title": "門框接口:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 6,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 10,
"formId": 1,
"title": "門框色澤:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 7,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 11,
"formId": 1,
"title": "磨耳及蟻油:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 8,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 12,
"formId": 1,
"title": "防火膠條:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 9,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 13,
"formId": 1,
"title": "平正及穩固:",
"checkType": 4,
"required": "Y",
"parentId": 3,
"orderNum": 10,
"answerVal": "Y",
"formDetailsOptions": []
},
{
"formDetailsId": 14,
"formId": 1,
"title": "備註:",
"checkType": 7,
"required": "N",
"parentId": 3,
"orderNum": 11,
"answerVal": "Test group remark",
"formDetailsOptions": []
}
]
}
]
},
{
"formDetailsId": 2,
"formId": 1,
"title": "B. 要改善位置及詳情備註:",
"checkType": 1,
"required": "Y",
"parentId": 0,
"orderNum": 2,
"answerVal": "Test B remark",
"formDetailsOptions": []
}
],
"formDefects": [
{
"formDefectsId": 1,
"formId": 1,
"defectRemark": "Test Remark",
"followActionId": 1,
"reporterType": 1,
"formDefectsImgs": [
{
"formDefectsImgId": 1,
"formDefectsId": 1,
"imgType": 1,
"filePath": "data/images/1/DEFECT-20201228150623123-2F3F4H.jpg",
"orderNum": 1
}
]
}
],
"formVendors": [
{
"formVendorId": 2,
"formId": 1,
"vendorId": "3954",
"orderNum": 2,
"isNextVendor": "N",
"formVendorImgs": [
{
"formVendorImgId": 1,
"formVendorId": 2,
"filePath": "data/images/1/QUERY-20201228151423123-2FF2V4.png",
"orderNum": 1
}
],
"vendor": {
"vendorId": "3954",
"vendorDesc": "博西華",
"vendorDescDisp": "BSH"
}
}
],
"formNextVendors": [
{
"formVendorId": 1,
"formId": 1,
"vendorId": "3985",
"orderNum": 1,
"isNextVendor": "Y",
"formVendorImgs": [
{
"formVendorImgId": 2,
"formVendorId": 1,
"filePath": "data/images/1/QUERY-20201228151423123-VD5F5H.png",
"orderNum": 2
}
],
"vendor": {
"vendorId": "3985",
"vendorDesc": "瑞基",
"vendorDescDisp": "Zuki"
}
}
]
}

With this kind of complex json i would suggest using dart packages for serialization. For example:
https://pub.dev/packages/json_serializable
or
https://pub.dev/packages/built_value

If you can share Dart models, then use json_serializable package. That would make things easier. But...
...if you have to live with the JSON response that your colleague developed and you cannot share your models that convert from/to Json, one alternative would be to use https://app.quicktype.io/
I entered your JSON response and out came generated Dart code that seems legit, at a first glance at least.
Example from that code generation:
factory ComplexJson.fromJson(Map<String, dynamic> json) => ComplexJson(
formId: json["formId"],
formTypeId: json["formTypeId"],
formTemplateId: json["formTemplateId"],
version: json["version"],
history: historyValues.map[json["history"]],
refNum: json["refNum"],
dateOfAcceptance: json["dateOfAcceptance"],
dateOfReacceptance: json["dateOfReacceptance"],
blockId: json["blockId"],
floorId: json["floorId"],
flatId: json["flatId"],
isPublic: historyValues.map[json["isPublic"]],
locationId: json["locationId"],
fromFloorId: json["fromFloorId"],
toFloorId: json["toFloorId"],
elevationId: json["elevationId"],
isNextVendor: historyValues.map[json["isNextVendor"]],
isMultipleVendor: historyValues.map[json["isMultipleVendor"]],
formStatusId: json["formStatusId"],
checkResults: json["checkResults"],
submissionDate: json["submissionDate"],
submittedBy: json["submittedBy"],
siteId: json["siteId"],
formDetails: List<MDetail>.from(json["formDetails"].map((x) => MDetail.fromJson(x))),
formDefects: List<FormDefect>.from(json["formDefects"].map((x) => FormDefect.fromJson(x))),
formVendors: List<FormVendor>.from(json["formVendors"].map((x) => FormVendor.fromJson(x))),
formNextVendors: List<FormVendor>.from(json["formNextVendors"].map((x) => FormVendor.fromJson(x))),
);

Related

How to insert data on last item of an inner array in MongoDB

I am trying to insert data in the last element of an array in MongoDB. insert in the first element works using the 0 operator, but I'm confused about how to insert in the last element. To explain it, consider the following data:
[
{
"_id": "1",
"company": "turivius",
"forms": [
{
"current_version": 1,
"history": [
{
"content": [],
"layout": [],
"responses": [
{
"client_id": 100,
"response_date": datetime(2022, 5, 17, 3, 0),
"values": [
{
"field_id": 0,
"primeiro user": "primeiro form, resposta 1",
},
{
"field_id": 1,
"value": "aaa",
},
],
},
{
"client_id": 100,
"response_date": datetime(2022, 5, 17, 3, 0),
"values": [
{
"field_id": 0,
"primeiro user": "primeiro form, resposta 2",
},
{
"field_id": 1,
"value": "bbb",
},
],
},
],
"version": 0,
},
{
"content": [],
"layout": [],
"responses": [
{
"client_id": 100,
"response_date": datetime(2022, 5, 17, 3, 0),
"values": [
{
"field_id": 0,
"primeiro user": "primeiro form, resposta 1 v1",
},
{
"field_id": 1,
"value": "aaa",
},
],
}
],
"version": 1,
},
],
"id": "33b66684-24a9-4a45-a12f-27a330152ac8",
"is_active": True,
},
{
"current_version": 0,
"history": [],
"id": "fa2eb9a1-c7c4-4b64-b682-7f51658bc4ab",
"is_active": False,
},
],
"user_id": "1",
},
{
"_id": "2",
"company": "turivius",
"forms": [
{
"current_version": 0,
"history": [],
"id": "565656",
"is_active": True,
},
],
"user_id": "9999",
},
]
I want to insert data in the document with user_id = 1, form.id = 33b66684-24a9-4a45-a12f-27a330152ac8 and in the history array where the version = 1 I want to insert a new response:
{
"client_id": 100,
"response_date": datetime(2022, 5, 17, 3, 0),
"values": [
{
"field_id": 0,
"test": "test",
},
{
"field_id": 1,
"test2": "test3",
},
],
}
The history with version 1 is the last element, if I wanted insert in the first element the following code would works:
find_one_and_update(
{"$and": [{"user_id": "1"}, {"forms.id": '33b66684-24a9-4a45-a12f-27a330152ac8'}]},
{
"$push": {"forms.$.history.0.responses": data_here},
},
return_document=ReturnDocument.AFTER,
)
Is there anyway to do it that way or I need a more complex query to do it?
You want to add a new document to the responses array when those conditions are true:
{
user_id: '1',
'forms.id': '33b66684-24a9-4a45-a12f-27a330152ac8',
'forms.history.version': 1
}
forms is an array, so you want to update the array element that matches the condition, so you can use the $[identifier] operator. Inside the array of forms, you only want to update the history with a specific version, so you need to use the $[identifier] operator multiple times, the field you want to update would be like this:
forms.$[f].history.$[h].responses
f is the identifier of each elements in forms that matches the condition and h the elements of the history array that match the other condition. An arrayFilters object is used to define the conditions.
The complete query could be like this:
db.collection.update({
user_id: "1",
'forms.id': '33b66684-24a9-4a45-a12f-27a330152ac8',
'forms.history.version': 1
},
{
$push: {
'forms.$[f].history.$[h].responses': {
"client_id": 100,
"response_date": "datetime(2022, 5, 17, 3, 0)",
"values": [
{
"field_id": 0,
"test": "test",
},
{
"field_id": 1,
"test2": "test3",
},
],
}
}
},
{
arrayFilters: [
{
'h.version': 1
},
{
'f.id': '33b66684-24a9-4a45-a12f-27a330152ac8'
}
]
})
Working example at MongoDB playground

How to get all the files from the Moodle assignment in a course?

I want to get all the files from an assignment in Moodle. Is there a way to get all the files?
When I call core_course_get_contents from my local Moodle instance as
http://localhost:8077/webservice/rest/server.php?wstoken=11e2d8b7f8e21ca1804e41e9cac5a816&wsfunction=core_course_get_contents&courseid=4&moodlewsrestformat=json
I receive the response as:
[
{
"id": 22,
"name": "General",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 0,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": []
},
{
"id": 23,
"name": "Introduction",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 1,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": [
{
"id": 44,
"url": "http://localhost:8077/mod/assign/view.php?id=44",
"name": "Assignment",
"instance": 3,
"contextid": 99,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/assign/1613571924/icon",
"modname": "assign",
"modplural": "Assignments",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
}
},
{
"id": 46,
"url": "http://localhost:8077/mod/resource/view.php?id=46",
"name": "test(.txt)",
"instance": 24,
"contextid": 102,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/core/1613571924/f/text-24",
"modname": "resource",
"modplural": "Files",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"a:1:{s:10:\\\"printintro\\\";i:1;}\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
},
"contents": [
{
"type": "file",
"filename": "test.txt",
"filepath": "/",
"filesize": 935,
"fileurl": "http://localhost:8077/webservice/pluginfile.php/102/mod_resource/content/1/test.txt?forcedownload=1",
"timecreated": 1621949734,
"timemodified": 1621949744,
"sortorder": 1,
"mimetype": "text/plain",
"isexternalfile": false,
"userid": 2,
"author": "ABC",
"license": "unknown"
}
],
"contentsinfo": {
"filescount": 1,
"filessize": 935,
"lastmodified": 1621949744,
"mimetypes": [
"text/plain"
],
"repositorytype": ""
}
}
]
}
]
I want to get the files from the assignment. Is there a way to achieve this?

How to retrieve Forum/discussion attachments of a course in Moodle LMS?

I have to list all the attachments of a discussion in a course. I don't know how to retrieve all the attachments URLs in a forum/discussion in Moodle LMS.
My code is in c# and usually, I call the Moodle REST API as http://localhost:8077/webservice/rest/server.php?wstoken=11e2d8b7f8e21ca1804e41e9cac5a812&wsfunction=core_course_get_contents&courseid=4&moodlewsrestformat=json and I can get the fileurl for the course files.
Likewise, I would like to retrieve forum/discussion files but I don't see any fileurl or something similar.
I only see the response as below:
[
{
"id": 22,
"name": "General",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 0,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": []
},
{
"id": 23,
"name": "Introduction",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 1,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": [
{
"id": 46,
"url": "http://localhost:8077/mod/resource/view.php?id=46",
"name": "Everest (.txt)",
"instance": 24,
"contextid": 102,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/core/1613571924/f/text-24",
"modname": "resource",
"modplural": "Files",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"a:1:{s:10:\\\"printintro\\\";i:1;}\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
},
"contents": [
{
"type": "file",
"filename": "Everest.txt",
"filepath": "/",
"filesize": 935,
"fileurl": "http://localhost:8077/webservice/pluginfile.php/102/mod_resource/content/1/Everest.txt?forcedownload=1",
"timecreated": 1621949734,
"timemodified": 1621949744,
"sortorder": 1,
"mimetype": "text/plain",
"isexternalfile": false,
"userid": 2,
"author": "DP Bhatt",
"license": "unknown"
}
],
"contentsinfo": {
"filescount": 1,
"filessize": 935,
"lastmodified": 1621949744,
"mimetypes": [
"text/plain"
],
"repositorytype": ""
}
},
{
"id": 47,
"url": "http://localhost:8077/mod/forum/view.php?id=47",
"name": "Forum",
"instance": 5,
"contextid": 112,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/forum/1613571924/icon",
"modname": "forum",
"modplural": "Forums",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
}
}
]
}
]
It would be great if someone guides me on the right path. Thank you very much in advance.

Sort multiple condition MongoDB

I have collection of user, and this is the following of documents :
{ "_id": 1, "name": "A", "online": 1, "like": 10, "score": 1 },
{ "_id": 2, "name": "B", "online": 0, "like": 9, "score": 0 },
{ "_id": 3, "name": "C", "online": 0, "like": 8, "score": 1 },
{ "_id": 4, "name": "D", "online": 1, "like": 8, "score": 0 },
{ "_id": 5, "name": "E", "online": 1, "like": 7, "score": 1 },
{ "_id": 6, "name": "F", "online": 0, "like": 10, "score": 1 },
{ "_id": 7, "name": "G", "online": 0, "like": 5, "score": 0 },
{ "_id": 8, "name": "H", "online": 0, "like": 13, "score": 0 }
{ "_id": 9, "name": "I", "online": 0, "like": 6, "score": 0 }
I want to show the list of users with some of criterias and ordering with some conditons, online users and most liked in the top of the list,after online user list is show offline users with most scored & most liked. The following of rules :
If online is 1 must be sort by descending of like.
If online is 0 and score is 1 must be sort by descending of score.
If online is 0 and score is 0 must be sort by descending of like.
So, the result can be like :
{ "_id": 1, "name": "A", "online": 1, "like": 10, "score": 1 },
{ "_id": 4, "name": "D", "online": 1, "like": 8, "score": 0 },
{ "_id": 5, "name": "E", "online": 1, "like": 7, "score": 1 },
{ "_id": 6, "name": "F", "online": 0, "like": 10, "score": 1 },
{ "_id": 3, "name": "C", "online": 0, "like": 8, "score": 1 },
{ "_id": 8, "name": "H", "online": 0, "like": 13, "score": 0 }
{ "_id": 2, "name": "B", "online": 0, "like": 9, "score": 0 },
{ "_id": 9, "name": "I", "online": 0, "like": 6, "score": 0 },
{ "_id": 7, "name": "G", "online": 0, "like": 5, "score": 0 }
I have finished until point 2, my query following :
db.users.aggregate([
{
$project :
{
"id" : 1,
"name" : 1,
"online: 1,
"like" : 1,
"score" : 1,
"sort" : {
$cond:
{
"if" :
{
$eq : ["$online", true]
},
"then" : "$like",
"else" : "$score"
}
}
}
},
{
$sort :
{
"online" : -1,
"sort" : -1,
"id" : 1
}
},
{
$skip : 0
},
{
$limit : 9
}
])
But I have the current result following :
{ "_id": 1, "name": "A", "online": 1, "like": 10, "score": 1 },
{ "_id": 4, "name": "D", "online": 1, "like": 8, "score": 0 },
{ "_id": 5, "name": "E", "online": 1, "like": 7, "score": 1 },
{ "_id": 6, "name": "F", "online": 0, "like": 10, "score": 1 },
{ "_id": 3, "name": "C", "online": 0, "like": 8, "score": 1 },
{ "_id": 2, "name": "B", "online": 0, "like": 9, "score": 0 },
{ "_id": 7, "name": "G", "online": 0, "like": 5, "score": 0 },
{ "_id": 8, "name": "H", "online": 0, "like": 13, "score": 0 }
{ "_id": 9, "name": "I", "online": 0, "like": 6, "score": 0 },
You can see, based on point 3, instance { "_id": 8, "name": "H", "online": 0, "like": 13, "score": 0 } should be on top with score is 0
First create additional column call point with value (1 - online)*score
After this sort data by:
online desc
point desc (online = 1 pointbe always 0, online is 0 point is score)
like desc
You can use this query
db.yourtable.aggregate(
[
{ $project:{
"id" : 1,
"name" : 1,
"online": 1,
"like" : 1,
"score" : 1,
point: { $multiply: [
{$subtract: [1,"$online"]}
, "$score"
]}
}
}
,{ $sort : { online: -1, point : -1, like : -1 } }
]
);
Please check below query :
db.getCollection('yourTable').aggregate([
{
$project :
{
"id" : 1,
"name" : 1,
"online": 1,
"like" : 1,
"score" : 1,
onlineSortLike: {
$cond: {
if: { $and: [{ $eq: ['$online',1 ] }] },
then: '$like',
else: 0,
},
},
sortOfflineScore: {
$cond: {
if: { $and: [{ $eq: ['$online',0] }] },
then: '$score',
else: 0,
},
},
sortOfflineScoreLike: {
$cond: {
if: { $and: [{ $eq: ['$online', 0] }] },
then: '$like',
else: 0,
},
},
}
},
{
$sort :
{
"online" : -1,
"onlineSortLike" : -1,
"sortOfflineScore" : -1,
"sortOfflineScoreLike" : -1
}
},
{
$skip : 0
},
{
$limit : 9
}
])

Magento 2: Store in array level 3 category using Rest API

I'm using REST API with Magento 2.2.3. Below you can see the JSON response when I try to get the category tree.
{
"id": 2,
"parent_id": 1,
"name": "Only Beauty",
"is_active": true,
"position": 1,
"level": 1,
"product_count": 0,
"children_data": [
{
"id": 1372323,
"parent_id": 2,
"name": "Cura della Pelle",
"is_active": true,
"position": 1,
"level": 2,
"product_count": 0,
"children_data": [
{
"id": 1372335,
"parent_id": 1372323,
"name": "Creme Idratanti Viso",
"is_active": true,
"position": 1,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1372377,
"parent_id": 1372323,
"name": "Taglie da Viaggio",
"is_active": true,
"position": 2,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1372535,
"parent_id": 1372323,
"name": "Detergenti Viso",
"is_active": true,
"position": 3,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1375522,
"parent_id": 1372323,
"name": "Struccanti",
"is_active": true,
"position": 4,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1375540,
"parent_id": 1372323,
"name": "Altri Prodotti per la Pelle",
"is_active": true,
"position": 5,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1375649,
"parent_id": 1372323,
"name": "Esfolianti & Scrubs",
"is_active": true,
"position": 6,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1375716,
"parent_id": 1372323,
"name": "Anti-Età",
"is_active": true,
"position": 7,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1375816,
"parent_id": 1372323,
"name": "Prodotti per Cura Occhi",
"is_active": true,
"position": 8,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1375930,
"parent_id": 1372323,
"name": "Maschere & Esfolianti",
"is_active": true,
"position": 9,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1376342,
"parent_id": 1372323,
"name": "Prodotti Pelle per Uomo",
"is_active": true,
"position": 10,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1376883,
"parent_id": 1372323,
"name": "Creme da Notte",
"is_active": true,
"position": 11,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1486731,
"parent_id": 1372323,
"name": "Controllo Acne e Macchie della Pelle",
"is_active": true,
"position": 12,
"level": 3,
"product_count": 0,
"children_data": []
}
]
},
{
"id": 1372324,
"parent_id": 2,
"name": "Fragranze",
"is_active": true,
"position": 2,
"level": 2,
"product_count": 0,
"children_data": [
{
"id": 1372341,
"parent_id": 1372324,
"name": "Per Lui",
"is_active": true,
"position": 1,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1372347,
"parent_id": 1372324,
"name": "Per Lei",
"is_active": true,
"position": 2,
"level": 3,
"product_count": 0,
"children_data": []
},
{
"id": 1372583,
"parent_id": 1372324,
"name": "Unisex",
"is_active": true,
"position": 3,
"level": 3,
"product_count": 0,
"children_data": []
}
]
}
I need to store in array the ID of all level 3 subcategory using rest API request.
I tried to get ID using the following code:
$authToken = getToken();
$cat = getCategory( $authToken );
foreach ( $cat["children_data"] as $key => $row ) {
if ( $row["level"] == 3 ) {
$array_cat[] = $row["id"];
}
}
This is the API request function:
function getCategory( $token ) {
$ch = curl_init( "https://www.onlybeauty.shop/rest/V1/categories/" );
curl_setopt_array( $ch, array(
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer '.$token,
),
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
));
$response = curl_exec( $ch );
if( $response === FALSE ) {
die( curl_error( $ch ) );
}
$responseData = json_decode( $response, TRUE );
return $responseData;
}
Seems that this code works only for level 2 subcategory.
Thanks in adv.
Your code works only for level 2 because you need to go deeper in the "array-tree" of decoded json categories response.
Meaning your foreach procedure should be something like this:
$my_data = json_decode($my_json, 1);
print_r($my_data);
$level2_cat = $my_data["children_data"];
foreach($level2_cat as $key=>$row){
print_r($row["children_data"][0]["level"]);
}
Just tried an example with a sample of your json and with this you print the level of the third level category. Hope it helps