From: Oren Ben-K. <or...@be...> - 2009-08-25 21:09:31
|
On Tue, 2009-08-25 at 09:51 -0700, William Spitzak wrote: > A much more interesting question about yaml: > > I doubt we are unique in that the data we wish to store is an array of > objects, all of them are different subclasses of some base object, and > the fields of these subclasses are different, and "which subclass" is > not predictable. > > What I propose to do to write an array containing them like this (where > both classes have a 'name' field, but class A has an 'a' field and class > B has a 'b' field: > > - !A {name: nameofa, a: value of a} > - !B {name: nameofb, b: value of b} > - !A {name: nameofa2, a: value} > ... > > Is this the planned usage of the type tags? Note that the 'b' field will > produce an error if placed in the A object. Yes, this makes perfect sense. Of course you have another option: look in the hash table and decide whether to load it to an A or a B depending on whether you see an 'a' key or a 'b' key. The details on how to do that depend on the specific YAML library used, and you _will_ need to create a temporary hash table, but this is explicitly allowed by the spec. > Another post here suggested this: > > - {type: A, name: nameofa, a: value of a} > - {type: B, name: nameofb, b: value of b} > - {type: A, name: nameofa2, a: value} > ... > > However this seems to require that "type" be first, at least if we want > to read directly into the object, rather than have to make a temporary > name+value structure and then set the object after I get the type. > Obviously I can force the yaml file to have the type first but this > seems inconsistent with yaml's design. In general you can't force, or rely on, the order of the keys in the file. That is, in general someone may apply some tool to the file (say a pretty-printer) that will sort the keys alphabetically, or something, and then you'd be SOL. Using tags as in the previous example is the recommended way. Or, you may accept the overhead of creating the temporary structure. > Am I using it as intended? Any other alternatives I missed? Nope, these are pretty much the two options you have. Tags or temporary structure. Actually... you _could_ mess up the file structure and do something like: - a: { name: nameofa, a: value of a } - b: { name: nameofb, b: value of b } But that's really just a dirtier form of tagging. Have fun, Oren Ben-Kiki |