Wednesday, August 14, 2013

JSON in Scilab

Hi dears, today I've met a tool for Scilab that makes possible to handle JSON files into Scilab code. This tool is available through ATOMS or in http://forge.scilab.org/index.php/p/json/

Once installed, let's make a simple test with this tool just for validation.

First, it's created a json file (json_test.json) like below:

{
  "orderID": 12345,
  "softwareName": "Scilab",
  "ToolName": "JSon",
  "contents": [
    {
      "productID": 1,
      "productName": "Test1",
      "quantity": 1
    },
    {
      "productID": 2,
      "productName": "Test2",
      "quantity": 3
    }
  ],
  "demoCompleted": true
}


Now, it's needed to get this file into Scilab, what we can do uding mgetl(.) function:

json_test = mgetl("file_test.json");

Take attention for the path of the file.

And the function JSONParse(.) returns the struct that corresponds to the data in the file, like this:

mystruct = JSONParse(json_test)

The expected result is

-->mystruct
 mystruct  =

   orderID: 12345
   softwareName: "Scilab"
   ToolName: "JSon"
   contents: [1x2 struct]
   demoCompleted: "%T"


For accessing the fields, try this:

-->mystruct.orderID
 ans  =

    12345. 

-->mystruct.ToolName
 ans  =

 JSon  

-->mystruct.contents.productName
 ans  =


       ans(1)

 Test1  

       ans(2)

 Test2  



JSON is like XML pattern, much used for WebServices and in other Internet cases. Thus, I recommend to spend a few time taking a look about this technology and how Scilab can aggregate value to your solutions.