Convert JSON to Table and Query Specific Value

조회 수: 45 (최근 30일)
Monkey Coder
Monkey Coder 2023년 8월 15일
댓글: Monkey Coder 2023년 8월 16일
I have the following JSON array:
{"views":[{"Name":"A","Conf":"High","View":"Negative"}, {"Name":"B","Conf":"Low","View":"Negative"}, {"Name":"C","Conf":"Low","View":"Negative"}]}
How can I convert it to Table? Also, how can I query a specific row of the table? (Example: Find value of "Conf" where Name is "C.)
So far I have:
jsonData = '{"views":[{"Name":"A","Conf":"High","View":"Negative"}, {"Name":"B","Conf":"Low","View":"Negative"}, {"Name":"C","Conf":"Low","View":"Negative"}]}'
structData = jsondecode(jsonData);

채택된 답변

Florian Bidaud
Florian Bidaud 2023년 8월 15일
편집: Florian Bidaud 2023년 8월 15일
jsonData = '{"views":[{"Name":"A","Conf":"High","View":"Negative"}, {"Name":"B","Conf":"Low","View":"Negative"}, {"Name":"C","Conf":"Low","View":"Negative"}]}'
jsonData = '{"views":[{"Name":"A","Conf":"High","View":"Negative"}, {"Name":"B","Conf":"Low","View":"Negative"}, {"Name":"C","Conf":"Low","View":"Negative"}]}'
structData = jsondecode(jsonData)
structData = struct with fields:
views: [3×1 struct]
structDataTable = struct2table(structData.views)
structDataTable = 3×3 table
Name Conf View _____ ________ ____________ {'A'} {'High'} {'Negative'} {'B'} {'Low' } {'Negative'} {'C'} {'Low' } {'Negative'}
structDataTable.Name
ans = 3×1 cell array
{'A'} {'B'} {'C'}
structDataTable.Conf{[structDataTable.Name{:}]=='C'}
ans = 'Low'
  댓글 수: 8
Florian Bidaud
Florian Bidaud 2023년 8월 16일
편집: Florian Bidaud 2023년 8월 16일
when you affect your value, first check if it's empty or not:
if ~isempty(structDataTable.Conf{strcmp([structDataTable.Name(:)],'Cat')})
value = structDataTable.Conf{strcmp([structDataTable.Name(:)],'Cat')};
else
value = nan;
end
Monkey Coder
Monkey Coder 2023년 8월 16일
sorry, I am getting "Unable to perform assignment with 0 elements on the right-hand side." on the following line.
if ~isempty(structDataTable.Conf{strcmp([structDataTable.Name(:)],'Cat')})

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by