Rest – Flat or nested JSON for hierarchal data

api-designjsonrest

I've switched back and forth ~5 times already. This REST endpoint at /api/tags/ will be for internal use (no 3rd party clients), I'm the only one working with it.

I'm deciding between these two representations:

Flat

{  
   "types":[  
      {  
         "id":1,
         "text":"Utility"
      },
      {  
         "id":7,
         "text":"Lease Terms"
      },
   ],
   "tags":[
      {  
         "id":8,
         "text":"Water",
         "type":1
      },
      {  
         "id":9,
         "text":"Electricity",
         "type":1
      },
      {  
         "id":5,
         "text":"Minimum 12 month lease",
         "type":7
      },
      {  
         "id":17,
         "text":"lease negotiable/flexible",
         "type":7
      },
   ]
}
  • It's somewhat modular. Can add another top layer such as "country" without breaking compatibility.

Nested

{  
   "1":{  
      "text":"Utility",
      "tags":{  
         "8":{  
            "text":"Water"
         },
         "9":{  
            "text":"Electricity"
         },
      }
   },
   "2":{  
      "text":"Lease Terms",
      "tags":{  
         "5":{  
            "text":"Minimum 12 month lease"
         },
         "17":{  
            "text":"lease negotiable/flexible"
         },
      }
   },
}
  • It's already in a usable format. Don't need to loop through data before using it.
  • Saves some bandwidth. Even after gzip, this is slightly smaller.

Which one should be used, and why? If this is a matter of personal preference, which representation would experienced developers prefer and why?

Best Answer

Depends on your use case.

When using JSON with statica typed languages, there is a huge bonus if your structure maps to your types. This means that all the names of the keys should be known in advance.

So, if you plan to use Java to consume the service, or if you plan to document it with JSON Schema, number one will be much cleaner (of course both will work).

Related Topic