Create Nested Structure with Arrays
45 views (last 30 days)
Show older comments
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...
}
0 Comments
Answers (1)
Ankriti Sachan
on 29 Oct 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.
0 Comments
See Also
Categories
Find more on JSON Format in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!