Save struct field names with hyphens/dash in JSON?
    11 views (last 30 days)
  
       Show older comments
    
    Olov Günther-Hanssen
 on 3 Apr 2020
  
    
    
    
    
    Commented: Walter Roberson
      
      
 on 11 Jul 2024
            It is quite common to use hyphens/dashes (-) in the field names of JSON, like this:
{
  "file-series-version" : "1.0",
  "files" : [
    { "name" : "foo1.vtk", "time" : 0 },
    { "name" : "foo2.vtk", "time" : 5.5 },
    { "name" : "foo3.vtk", "time" : 11.2 }
  ]
}
However, I haven't found a way to get a hyphen character into the JSON with the JSON encoder https://se.mathworks.com/help/matlab/ref/jsonencode.html as that has to be done through the field names of a struct, incorrectly like this
jsonObj = struct('file-series-version', 1); % This will generate 'Invalid field name "file-series-version".'
jsonencode(jsonObj)
So, is there any standardized way of creating these kind of JSON objects with the jsonencode function? My alternative would be to use camelCase on the field names, and regex over the JSON-string after encoding to convert them into kebab-case, but that is not a generally good idea.
0 Comments
Accepted Answer
  Harsha Priya Daggubati
    
 on 6 Apr 2020
        Hi,
A valid field name of a structure begin with a letter, and can contain letters, digits, and underscores. So use of hyphen for a fieldname is not supported in MATLAB. Use of camelCase, or using underscore instead of hyphen (you can use regular expression to convert to kebab-case later) sound as suitable workarounds for your issue.
3 Comments
  stedst9
 on 11 Jul 2024
				I'm having the same isssue.  I understand Matlab's field name requirements.  What is the fix (or workaround) to get hyphens/dashes (-) in the field names of JSON???
  Walter Roberson
      
      
 on 11 Jul 2024
				Use underscore in the field names. Generate the JSON. Modify the JSON 
S = readlines('AppropriateFilename.JSON');
S = regexprep(S, '_', '-');
writelines(S, 'AppropriateFilename.JSON')
More Answers (0)
See Also
Categories
				Find more on JSON Format in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


