Create Nested Structure with Arrays

43 次查看(过去 30 天)
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...
}

回答(1 个)

Ankriti Sachan
Ankriti Sachan 2020-10-29
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.

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by