Create Nested Structure with Arrays

38 ビュー (過去 30 日間)
Nicky Parekh
Nicky Parekh 2020 年 10 月 26 日
回答済み: Ankriti Sachan 2020 年 10 月 29 日
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.

カテゴリ

Help Center および File ExchangeJSON Format についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by