Create Nested Structure with Arrays

45 Ansichten (letzte 30 Tage)
Nicky Parekh
Nicky Parekh am 26 Okt. 2020
Beantwortet: Ankriti Sachan am 29 Okt. 2020
Hi,
I need to query an API that needs a file in JSON format (format below). I am having trouble using jsonencode to get to this format. I have three arrays (Nx1), fieldnames (eg. ["Request1";"Request2";...]), Method (eg.["GET";"GET;"GET"...]), and Resource (eg. [Custom1URL; Custom2URL,...]). How can I create a structure so that the format is struct.WebId1.Method, struct.WebId2.Method? I know I can do this using struct() but I need to automate it since eventually there can be >1000 requests. Thank you!
{
"Request1":
{
"Method":"GET",
"Resource":"URL"
},
"Request2":
{
(same format)
}
etc...
}

Antworten (1)

Ankriti Sachan
Ankriti Sachan am 29 Okt. 2020
Based on my understanding, you want to create a nested structure using the 3 arrays available to you.
I have created a small script to do the same. Please refer below:
req = ["Request1";"Request2"];
met = ["GET";"GET"];
res = ["URL1";"URL2"];
for i=1:length(req)
myValue = struct("Method", met{i}, "Resource", res{i});
myFieldname = req{i};
myStruct.(myFieldname) = myValue;
end
Here, you have a nested structure named 'myStruct.'
Structure "Request1" can be accessed using "myStruct.Request1." Its values can be accessed using "myStruct.Request1.Method," etc.

Produkte


Version

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by