THX-1138
THX-1138

Reputation: 21730

JSON schema : allow to store information in keys

I want to formally define a schema for a JSON-based protocol. I have two criteria for the schema: 1. I want to be able to use tools to create parser/serializer (php and .net). 2. Result JSON should be easy to human-read

Here is the context. The schema will be describing a game character, as an example I will take one aspect of the profile - professions. A character can have up to 2 professions (from a list of 10), each profession is described by a name and a level, e.g.:

Skinning - level 200 Blacksmith - level 300

To satisfy criterion #1 it really helps to have XSD schema (or JSON Schema) to drive code generator or a parser library. But that means that my JSON must look something like:

character : {
    professions : [ 
        { profession : "Skinning", level : 525 }
        { profession : "Blacksmith", level : 745 }
    ]
}

but it feels too chatty, I would rather have JSON look like (notice that profession is used as a key):

character {
    professions : {
        "Skinning" : 525,
        "Blacksmith" : 745 
    }
}

but the later JSON can not be described with XSD without having to define an element for each profession.

So I am looking for a solution for my situation, here are options I have identified:

  1. shut up and make JSON XSD-friendly (first snippet above)
  2. shut up and make JSON human-friendly and hand-code the parser/serializer.

but I would really like to find a solution that would satisfy both criteria.

Note: I am aware that Newton-King's JSON library would allow me to parse professions as a Dictionary - but it would require me to hand code the type to map this JSON to. Therefore so far I am leaning towards option #2, but I am open to suggestions.

Upvotes: 1

Views: 420

Answers (2)

CedricB
CedricB

Reputation: 1167

Your options are, as you said... 1 shut up and use xml 2 shut up and build your own

OR maybe 3... http://davidwalsh.name/json-validation

I would do #1 - because xml seems to be a fairly common way to transform stuff from X => Y formats - I prefer to work in C# not JS - many people use XML, its an accepted standard, there are many resources out there to help you along the way

Upvotes: 0

eggie5
eggie5

Reputation: 1960

Rename profession to name so it'd be like:

character : {
    professions : [ 
        { name : "Skinning", level : 525 }
        { name : "Blacksmith", level : 745 }
    ]
}

Then after it's serialized on the client model would be like this:

profession = character.professions[0]
profession.name
=> "Skinning"

Upvotes: 1

Related Questions