Convert Struct to Readable JSON(Pretty Print)

237 ビュー (過去 30 日間)
ILoveMATLAB
ILoveMATLAB 2019 年 9 月 4 日
コメント済み: John Wittig 2024 年 3 月 8 日
Every struct I pass to jsonecode gets converted to a 1 by N char array with no newline chacters. Therefore, when I export the json as to a text file I only have one line. The file is not easly readble because I have to scroll the JSON text horizontaly. How can I make jsonencode's output easily readable(pretty print)?
I get this.
{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "3 Apple Hill Dr", "city": "Natick", "state": "MA", "postalCode": "01760" }, "phoneNumber": [ { "type": "home", "number": "123 456 7890" }, { "type": "cell", "number": "098 765 4321" } ] }
I want something like this.
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address":
{
"streetAddress": "3 Apple Hill Dr",
"city": "Natick",
"state": "MA",
"postalCode": "01760"
},
"phoneNumber":
[
{
"type": "home",
"number": "123 456 7890"
},
{
"type": "cell",
"number": "098 765 4321"
}
]
}
  5 件のコメント
Davide Serina
Davide Serina 2022 年 12 月 8 日
移動済み: DGM 2022 年 12 月 8 日
ciao, come si fa ad ottenere una struttura come quella che hai scritto partendo da una struttura su matlab?! cioè non riesco a fare gli annidamenti. bisogna usare un ciclo for???
Sean Bone
Sean Bone 2022 年 12 月 9 日
Ciao @Davide Serina, la tua domanda si riferisce a come creare una struttura annidata in MATLAB o a come convertire una struttura annidata in JSON? Oppure ancora a come convertire una struttura MATLAB in JSON con le indentature per rappresentare gli annidamenti?

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

採用された回答

Sean Bone
Sean Bone 2022 年 1 月 30 日
In more recent Matlab versions, you can do the following:
jsonencode(data, "PrettyPrint", true);
Note that this option was only introduced in Matlab R2021a, despite the documentation for jsonencode not mentioning this explicitly.
  1 件のコメント
ILoveMATLAB
ILoveMATLAB 2022 年 5 月 17 日
I guess I will accept this anwser; although, I was using an older version of matlab when I wrote this question.

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

その他の回答 (2 件)

Robin Larsson Nordström
Robin Larsson Nordström 2023 年 10 月 3 日
編集済み: Robin Larsson Nordström 2023 年 10 月 3 日
For the provided example the default pretty print output will be fine:
txt=jsonencode(data, "PrettyPrint", true);
However if the input data struct contains fields with vectors or matrices the jsonencode PrettyPrint in Matlab 2023b adds a newline for each element, making the encoded text hard to read even when the number of elements are not that many.
Post-processing the output with a few regexprep lines to remove white-spaces inside vectors and matrices have worked well for me. Example below with the struct from the Matlab help on jsonencode PrettyPrint example with the addition of an extra field Q storing a 4 X 4 matrix:
s=[];
s.Width = 800;
s.Height = 600;
s.Title = 'View from the 15th Floor';
s.Animated = false;
s.IDs = [116, 943, 234, 38793];
s.Q = round(randn(4),3);
txt=jsonencode(s,PrettyPrint=true)
txt =
'{ "Width": 800, "Height": 600, "Title": "View from the 15th Floor", "Animated": false, "IDs": [ 116, 943, 234, 38793 ], "Q": [ [ 0.104, -1.164, -2.504, 1.22 ], [ -0.277, -1.496, 0.394, 2.864 ], [ 0.418, 0.155, -0.266, 0.515 ], [ 1.536, 0.02, 0.071, 1.06 ] ] }'
% remove white-spaces inside vectors and matrices
txt = regexprep(txt,',\s+(?=\d)',','); % , white-spaces digit
txt = regexprep(txt,',\s+(?=-)',','); % , white-spaces minussign
txt = regexprep(txt,'[\s+(?=\d)','['); % [ white-spaces digit
txt = regexprep(txt,'[\s+(?=-)','['); % [ white-spaces minussign
txt = regexprep(txt,'(?<=\d)\s+]',']'); % digit white-spaces ]
txt
txt =
'{ "Width": 800, "Height": 600, "Title": "View from the 15th Floor", "Animated": false, "IDs": [116,943,234,38793], "Q": [ [0.104,-1.164,-2.504,1.22], [-0.277,-1.496,0.394,2.864], [0.418,0.155,-0.266,0.515], [1.536,0.02,0.071,1.06] ] }'
  1 件のコメント
John Wittig
John Wittig 2024 年 3 月 8 日
very slick and helpful!

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


Gaurav Garg
Gaurav Garg 2019 年 11 月 20 日
Hi,
You can find a function which can help you resolve the problem you are facing in this file.
  1 件のコメント
Laurel Keyes
Laurel Keyes 2021 年 6 月 28 日
This file is helpful but not if you have nested structures. I use a quick and dirty method, where you just string-replace the commas or brackets like so:
% assuming your structure is saved to val:
str = jsonencode(val);
% add a return character after all commas:
new_string = strrep(str, ',', ',\n');
% add a return character after curly brackets:
new_string = strrep(new_string, '{', '{\n')
% etc...
% Write the string to file
fid = fopen("filename.json",'w')
fprint(fid, new_string);
fclose(fid);
This method will not indent but does allow a slightly better formatting, no matter the structure of your json

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

カテゴリ

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

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by