Clear Filters
Clear Filters

How to parse Dynamic JSON file in Simulink?

45 views (last 30 days)
Arhan Kundu
Arhan Kundu on 19 Jan 2022
Commented: Toby on 11 Apr 2024
Hi All,
I am currently working on a usecase where I have to parse dynamic json file in simulink model. I have tried using matlab function jsondecode in simulink function block but the function jsondecode is not supported for code generation. Is there any other way to parse json file in simulink?

Answers (1)

Riya
Riya on 16 Nov 2023
Hello Arhan,
As per my understanding you want to know how to parse Dynamic JSON file in Simulink.
Please note that one approach is to use a third-party JSON parsing library that is compatible with Simulink code generation. Here is an example of how you can achieve this using the "JSONlab" library:
1. Download the JSONlab library from the MATLAB File Exchange: https://www.mathworks.com/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files
2. Extract the downloaded files and add the JSONlab folder to your MATLAB path.
3. In your Simulink model, use a MATLAB Function block to parse the JSON file. Here's an example of how you can do this:
function parsedData = parseJSONFile(jsonFile)
% Load the JSONlab library
addpath('path/to/jsonlab');
% Read the JSON file
jsonStr = fileread(jsonFile);
% Parse the JSON string
parsedData = loadjson(jsonStr);
% Remove the JSONlab library from the MATLAB path
rmpath('path/to/jsonlab');
4. Connect the input of the MATLAB Function block to the JSON file path input and the output to the parsed data output.
5. Generate code from your Simulink model. The MATLAB Function block will use the JSONlab library for parsing the JSON file during code generation.
Make sure to replace `'path/to/jsonlab'` in the code above with the actual path to the JSONlab library on your system.
By using this approach, you can parse dynamic JSON files in Simulink even though the `jsondecode` function is not supported for code generation.
I hope it helps.
  1 Comment
Toby
Toby on 11 Apr 2024
This solution doesn't appear to work as the functions used to add jsonlab are not supported for code generation. The following error message appears:
Function 'addpath' not supported for code generation.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!