JSONlab examples: from JSON to MATLAB and back

1. Example 1
2. Example 2
3. Example 3
4. MATLAB struct demo
5. MATLAB array demo
6. MATLAB sparse array demo
7. Special characters in names

1. Example 1

example1.json (source: Wikipedia):

 {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address":
     {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber":
     [
         {
           "type": "home",
           "number": "212 555-1234"
         },
         {
           "type": "fax",
           "number": "646 555-4567"
         }
     ]
 }

Loading to matlab

 >> data=loadjson('example1.json')

 data = 

      firstName: 'John'
       lastName: 'Smith'
            age: 25
        address: [1x1 struct]
    phoneNumber: {[1x1 struct]  [1x1 struct]}

Saving to JSON format again

 >> savejson('',data)

 ans = {
	"firstName": "John",
	"lastName": "Smith",
	"age": 25,
	"address": {
		"streetAddress": "21 2nd Street",
		"city": "New York",
		"state": "NY",
		"postalCode": "10021"
	},
	"phoneNumber": [
		{
			"type": "home",
			"number": "212 555-1234"
		},
		{
			"type": "fax",
			"number": "646 555-4567"
		}
	]
 }

2. Example 2

example2.json (source: JSON homepage):

 {
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
 }

Loading to octave

 >> data=loadjson('example2.json')
data =
{
  glossary =
  {
    title = example glossary
    GlossDiv =
    {
      1x1 struct array containing the fields:

        title: 1x1 sq_string
        GlossList: 1x1 struct
    }

  }

}

Saving to JSON format again

 >> savejson('',data)

 ans = {
	"glossary": {
		"title": "example glossary",
		"GlossDiv": {
			"title": "S",
			"GlossList": {
				"GlossEntry": {
					"ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
						"para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": [
							"GML",
							"XML"
						]
					},
					"GlossSee": "markup"
				}
			}
		}
	}
 }

3. Example 3

example3.json (source: JSON homepage):

 {"menu": {
   "id": "file",
   "value": "_&File",
   "popup": {
     "menuitem": [
       {"value": "_&New", "onclick": "CreateNewDoc(\"\"\")"},
       {"value": "_&Open", "onclick": "OpenDoc()"},
       {"value": "_&Close", "onclick": "CloseDoc()"}
     ]
   }
 }}

Loading to octave

 >> data=loadjson('example3.json')

data =
{
  menu =
  {
    id = file
    value = _&File
    popup =
    {
      1x1 struct array containing the fields:

        menuitem: 1x3 struct
    }

  }

}

Saving to JSON format again

 >> savejson('',data)

 ans = {
	"data": {
		"menu": {
			"id": "file",
			"value": "_&File",
			"popup": {
				"menuitem": [
					{
						"value": "_&New",
						"onclick": "CreateNewDoc(\"\"\")"
					},
					{
						"value": "_&Open",
						"onclick": "OpenDoc()"
					},
					{
						"value": "_&Close",
						"onclick": "CloseDoc()"
					}
				]
			}
		}
	}
 }

4. MATLAB struct demo

Define a MATLAB structure, notice the handling to the special variables "NaN" and "Inf":

  a=struct('node',[1  9  10; 2 1 1.2], 'elem',[9 1;1 2;2 3],...
      'face',[9 01 2; 1 2 3; NaN,Inf,-Inf], 'author','FangQ');

octave:8> a
a =
{
  node =

      1.0000    9.0000   10.0000
      2.0000    1.0000    1.2000

  elem =

     9   1
     1   2
     2   3

  face =

       9     1     2
       1     2     3
     NaN   Inf  -Inf

  author = FangQ
}

Convert MATLAB data to JSON

 octave:10> savejson('obj',a)

ans = {
	"obj": {
		"node": [
			[1,9,10],
			[2,1,1.2]
		],
		"elem": [
			[9,1],
			[1,2],
			[2,3]
		],
		"face": [
			[9,1,2],
			[1,2,3],
			["_NaN_","_Inf_","-_Inf_"]
		],
		"author": "FangQ"
	}
}

Convert JSON string back to MATLAB variable

 octave:11> data=loadjson(savejson('obj',a))

data =
{
  obj =
  {
    node =

        1.0000    9.0000   10.0000
        2.0000    1.0000    1.2000

    elem =

       9   1
       1   2
       2   3

    face =

         9     1     2
         1     2     3
       NaN   Inf  -Inf

    author = FangQ
  }

}

5. MATLAB array demo

Using the same "a" structure, we force savejson to use specialized structure to save array

Convert MATLAB data to JSON

 octave:14> savejson('',a,struct('ArrayToStruct',1))

 ans = {
	"a": {
		"node": {
			"_ArrayType_": "double",
			"_ArraySize_": [2,3],
			"_ArrayData_": [1,2,9,1,10,1.2]
		},
		"elem": {
			"_ArrayType_": "double",
			"_ArraySize_": [3,2],
			"_ArrayData_": [9,1,2,1,2,3]
		},
		"face": {
			"_ArrayType_": "double",
			"_ArraySize_": [3,3],
			"_ArrayData_": [9,1,"_NaN_",1,2,"_Inf_",2,3,"-_Inf_"]
		},
		"author": "FangQ"
	}
 }

Convert JSON string back to MATLAB variable

Converting the string back producing the same MATLAB structure.
 octave:15> data=loadjson(ans)
data =
{
  a =
  {
    node =

        1.0000    9.0000   10.0000
        2.0000    1.0000    1.2000

    elem =

       9   1
       1   2
       2   3

    face =

         9     1     2
         1     2     3
       NaN   Inf  -Inf

    author = FangQ
  }

}

6. MATLAB sparse array demo

For sparse arrays, savejson uses _ArrayIsSparse_ keyword.

 a=sparse(100,100);
 a(11,9)=1;
 a(30,60)=10;
 savejson('',a)

 ans = {
	"_ArrayType_": "double",
	"_ArraySize_": [100,100],
	"_ArrayIsSparse_": 1,
	"_ArrayData_": [
		[11,9,1],
		[30,60,10]
	]
 }

Converting back producing the same sparse array:

 octave:20> data=loadjson(ans)

 data =
 Compressed Column Sparse (rows = 100, cols = 100, nnz = 2 [0.02%])
   (11, 9) ->  1
   (30, 60) ->  10

7. Special characters in names

In JSON, a "name" tag can be any valid Unicode strings (with escape sequences). However, MATLAB field/variable names can only use [a-zA-Z0-9_]. To convert an arbitrary JSON string, we have to convert these "invalid" characters into a valid MATLAB variable names. Here is an example

 octave:21> data=loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"test"}')

data =
{
  ValidName =  1
  x0x5F_InvalidName =  2
  x0x3A_Field_0x3A_ =  3
  x0xE9__0xA1__0xB9__0xE7__0x9B__0xAE_ = test
}

Notice that a MATLAB variable name can only start with a letter. If the leading character is not a letter, loadjson converts it to a form of "x0xXX_" where XX represents a hex code. An invalid character that is not in a leading position will be converted to "_0xXX_". Notice, that the output for multi-byte characters (MBC) is sensitive to the current character set setting in the MATLAB. For example, if the setting is "UTF-8", the last field name in the last example, "项目" (in Chinese), is "x0xE9A1B9__0xE79BAE_", where the two Chinese characters were interpreted as unicode (UTF-8). If the setting is "latin1", the output is "x0xE9__0xA1__0xB9__0xE7__0x9B__0xAE_", same as the Octave output. We suggest one to run

  feature('DefaultCharacterSet','latin1')
first in MATLAB to get more consistent results.
Powered by Habitat