Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for documenting a JSON file structure? [closed]

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?

like image 862
Johannes Ernst Avatar asked Nov 05 '22 11:11

Johannes Ernst


2 Answers

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.

like image 159
ken Avatar answered Nov 11 '22 18:11

ken


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"]
}
like image 27
R. Oosterholt Avatar answered Nov 11 '22 19:11

R. Oosterholt