How to open multiple .json files and parse the data in it in automated way?

15 次查看(过去 30 天)
In each .json file, there are mixtue of string and numbers. All .json files have the same struncture but numbers/strings changes in each file.
I was wondering if there is matlab fucntion that I can extract info from each json file similar to the excel file. In excel file we can call a specific column, a specific row and a specifi cell playing wtih string and numbers (e.g. A1, B2, or so). I need to do something similar in .json but do not know how to parse through the file.

回答(1 个)

Aniket
Aniket 2025-3-5
MATLAB provides jsondecode function to parse JSON into MATLAB structures and then access specific elements similar to how you reference Excel cells. Kindly follow below mentioned steps to parse JSON in MATLAB:
  1. Read JSON file as a string using fileread
  2. Decode the JSON structure using jsondecode
  3. Access the required fields using structure indexing.
Example:
Consider you have a JSON file (data.json):
{
"A": {"a": 100, "b": 200},
"B": {"a": "Hello", "b": "World"}
}
This file can be read and extracted like shown below:
jsonStr = fileread('data.json');
data = jsondecode(jsonStr);
% Access specific data (like Excel cells A1, B2, etc.)
column = 'A';
row = 'a';
value = data.(column).(row); % Access "A.a" (100)
disp(value); % Output: 100
Please ensure that the fieldnames in JSON structure are valid MATLAB identifiers as mentioned in this documentation:
Invalid names in the JSON text are made valid with matlab.lang.makeValidName.
I hope this helps achieve the functionality you desired.

Community Treasure Hunt

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

Start Hunting!

Translated by