File Exchange Pick of the Week

Our best user submissions

Parsing JSON files

Jiro's pick this week is JSONlab by Qianqian Fang.

Recently, I've been working quite a bit with JSON files. I needed a way to read the files and parse out some content. With structured files like these, it's not terribly difficult to find tags and extract out information. But it does take some time. I started to write a program to do this.

What was I thinking?! Why re-invent the wheel when, most likely, someone has already done this before. It turns out that there are already a few File Exchange entries for dealing with JSON formats. Almost any of them would have helped me, but Qianqian's JSONlab caught my eyes. His entry directly handled JSON files, as opposed to JSON strings.

Let's see it in action. Suppose that there is a JSON file, "example.json", whose content is this.

 {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address":
     {
         "streetAddress": "3 Apple Hill Dr",
         "city": "Natick",
         "state": "MA",
         "postalCode": "01760"
     },
     "phoneNumber":
     [
         {
           "type": "home",
           "number": "123 456 7890"
         },
         {
           "type": "cell",
           "number": "098 765 4321"
         }
     ]
 }

You can extract the content like this.

data = loadjson('example.json');

Let's take a look.

disp(data)
      firstName: 'John'
       lastName: 'Smith'
            age: 25
        address: [1x1 struct]
    phoneNumber: {[1x1 struct]  [1x1 struct]}
disp(data.address)
    streetAddress: '3 Apple Hill Dr'
             city: 'Natick'
            state: 'MA'
       postalCode: '01760'
disp(data.phoneNumber{1})
      type: 'home'
    number: '123 456 7890'
disp(data.phoneNumber{2})
      type: 'cell'
    number: '098 765 4321'

In addition to decoding JSON files into MATLAB structures, the package lets you convert MATLAB structures into JSON format strings, as well as deal with binary JSON formats.

Thanks Qianqian! You saved me some time with my work!

Comments

Give this a try and let us know what you think here, or leave a comment for Qianqian.




Published with MATLAB® R2015a

|
  • print

コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。