javascript - How to express types in JSON? -
i want store tree data using json, can't figure out how express types nicely.
below how xml hypothetical game involving cats , mice like:
<level> <entities> <cat> <direction>right</direction> <position x="100" y="100"/> </cat> <mouse> <direction>right</direction> <position x="50" y="50"/> </mouse> </entities> </level>
the best json can come follows:
{ "entities": [ { "type": "cat", "direction": "right", "position": {"x": 100, "y": 100} }, { "type": "mouse", "direction": "right", "position": {"x": 50, "y": 50} } ] }
here specify type explicitly. seems xml better fit this, unfortunately, can't use it, i'm wondering if there's nicer way json.
inspired lua's table constructors, came following, not json, js fine in case (this data not intended transfered, it's tree of objects):
{ "entities": [ cat({ "direction": "right", "position": {"x": 100, "y": 100} }), mouse({ "direction": "right", "position": {"x": 50, "y": 50} }) ] };
but, in lua, downside have define possible entities functions somewhere:
function cat(options) { options.type = "cat"; return options; } function mouse(options) { options.type = "mouse"; return options; }
what think, there better way express types in json have attribute that? hack going far?
if types unique, use this
var entities = { cat : { direction: "right", position: {x: 100, y: 100} }, mouse : { direction: "right", position: {x: 50, y: 50} } };
then if want access different types, use
object.keys(entities) // outputs ["cat","mouse"]
edit after comment :
what way ?
var entities = { cat : [{ direction: "right", position: {x: 100, y: 100} },{ direction: "top", position: {x: 150, y: 150} }], mouse : [{ direction: "right", position: {x: 50, y: 50} }] };
Comments
Post a Comment