How to update json file with MATLAB?

58 ビュー (過去 30 日間)
Yaser Khojah
Yaser Khojah 2020 年 2 月 9 日
コメント済み: Kojiro Saito 2022 年 3 月 3 日
I have json file that is read by MATLAB script. I’m looking for a way to update the file since there are many to update. I know I can fixed the MATLAB script but I want to keep it and just fix the details in the json file.
I could not upload the json file since it does not accept it here. I converted to a txt one.
What I need to do is the following (in row 209)
For example. I have "HighPrice" :12000 and I want to change it to "HighPrice" :11000,
Anyway, MATLAB can fix this rather than doing it manually please?

採用された回答

Kojiro Saito
Kojiro Saito 2020 年 2 月 10 日
From R2016b, MATLAB can handle JSON format easily with jsondecode and jsonencode.
Here is a snippet to change the value of JSON and write to a file.
jsonText = fileread('Portfolio.json');
% Convert JSON formatted text to MATLAB data types (3x1 cell array in this example)
jsonData = jsondecode(jsonText);
% Change HighPrice value in Row 3 from 10000 to 12000
jsonData{3}.HighPrice = 12000;
% Convert to JSON text
jsonText2 = jsonencode(jsonData);
% Write to a json file
fid = fopen('Portfolio2.json', 'w');
fprintf(fid, '%s', jsonText2);
fclose(fid);
  4 件のコメント
Roger Dettloff
Roger Dettloff 2022 年 3 月 3 日
For a more human readable output:
jsonText2 = jsonencode(jsonData,'PrettyPrint',true);
Kojiro Saito
Kojiro Saito 2022 年 3 月 3 日
Yes, 'PrettyPrint' option in jsonencode is available from R2021a.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by