Trouble with jsondecode() and jsonencode()

55 views (last 30 days)
Rui Zhang
Rui Zhang on 3 May 2021
Commented: Rui Zhangon 3 May 2021
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:
在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 Comments
the cyclist
the cyclist on 3 May 2021
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.)

Sign in to comment.

Answers (1)

Sean de Wolski
Sean de Wolski on 3 May 2021
fprintf(fid,"%s",str2)
That way if there are format spec characters in the JSON they are not interpretted as such.
1 Comment
Rui Zhang
Rui Zhang on 3 May 2021
It works.
Thank you!
Rui

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!