Trouble with jsondecode() and jsonencode()

I have a JSON file. I am trying to test the MATLAB functions before using them. So I loaded it
str1 = fileread('json_filename1.json');
mydata1 = jsondecode(str1)
str2 = jsonencode(mydata1)
fid = fopen('json_filename2.json','wt')
fprintf(fid,str2)
fclose(fid)
Then I go to the online JSON file editor: https://jsoneditoronline.org/#left=local.jagoxe to load both files. I am able to load 'json_filename1.json' but I can't load 'json_filename2.json' correctly. I got the following error message:
Failed to switch to "tree" mode because of Invalid JSON:
Parse error on line 1:
...,"errorDescription":"CreateACPath Execut
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
It looks like either jsondecode() or jsonencode() has something wrong.
Also, when I used strcmp(str1,str2), I saw a lot of difference between them.

3 件のコメント

the cyclist
the cyclist 2021 年 5 月 3 日
Can you upload the original JSON file here, so that we can test to see what is going on?
Rui Zhang
Rui Zhang 2021 年 5 月 3 日
Hello,
Could you provide me your email address so I can send it to you by email? I don't want to post the JSON file here in a public place.
Thanks.
Rui
the cyclist
the cyclist 2021 年 5 月 3 日
No, sorry.
But perhaps you could distill your JSON down to a simplified and/or obscured version that still shows the problem, but you are comfortable sharing? (This may also help narrow down exactly what is causing the issue.)

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

回答 (1 件)

Sean de Wolski
Sean de Wolski 2021 年 5 月 3 日

2 投票

fprintf(fid,"%s",str2)
That way if there are format spec characters in the JSON they are not interpretted as such.

2 件のコメント

Rui Zhang
Rui Zhang 2021 年 5 月 3 日
It works.
Thank you!
Rui
Isaac Asher
Isaac Asher 2024 年 7 月 29 日
Awesome - I needed this to ensure that one of my fields in the JSON (a path to a file) got saved & loaded correctly. Otherwise it got messed up due to the slashes / escape characters.

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

タグ

質問済み:

2021 年 5 月 3 日

コメント済み:

2024 年 7 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by