I want others to be able to create JSON files that my code can understand. How would I best document what the required / allowed structure is?
Example:
{
"customer1" : {
"open-orders" : [
123,
456
],
"terms" : [
"net 30"
]
}, ...
}
How would I state stuff like "on the first level, it's the customer ID as found in the CRM system. Then 'terms' is required to be there and may have between 1 and 3 items in the array. You must not ever call a first-level tag 'error' but all other unknown tags are ignored etc. etc."
In XML I could use a DTD that already captures some of this information, and I could add some additional comments.
But what's best practice for JSON? Right now I'm playing with a table structure where in the left column I have a valid JSON file according to my structure, which is chopped into chunks, each of which is a row in the table. In the right columns, I then write prose, one chunk/row at a time. I'm not too happy with it. Are there better ideas?
JSON is just a serialized representation of your data-structure(s); as such, you should document the data-structure(s) in lieu of the serialized output.
/**
* @var object Customer
*/
var customer = {
/**
* @var Number[][]
*/
"open-orders": [],
/**
* @var String[][]
*/
"terms": []
};
Also, JSON does not have any data-specification (markup) notation, like XML; whereas XML can also be used to serialize data, it lets you specify the structure of the data (with XSD's). JSON was not intended to do this and provides no mechanisms for such.
You could write a schema for the json structure (just like a dtd for XML files).
Here's a good place to start: http://json-schema.org
Example:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With