4 ms·
> structure = json.loads(json_string) Not quite. Let's say your JSON data contains the following attribute: "access" : [ "view", "edit", "admin" ], Th
by Arkadir 12y ago
> structure = json.loads(json_string)
Not quite. Let's say your JSON data contains the following attribute:
"access" : [ "view", "edit", "admin" ],
This field should be represented (in the language) as a set of values from an "access-levels" enumeration.
In C#, you'd have the following boilerplate:
[DataMember(Name = "access")]
public HashSet<AccessLevels> Access { get; private set; }
In OCaml, it would be:
access : Access.Set.t ;
The simple "json.loads" solution would return a list of strings instead. What's the Python code for turning it into a set of enumeration values, and failing if one of the values does not match ?
- falcolas 12y agoPython doesn't have enumerations, per se. Here's how I'd represent that: if 'edit' in structure['access']: # can edit In which case it really doesn't matter if there's junk in access. If I really felt the need to validate the structure, I could do so with: if not set(structure['access']).issubset(all_access_privs): raise ValueError('invalid access types passed in') but more realistically, I'd rely on the ORM object to validate against the authoritative source - the database - and key off the errors there.
- TomaszZielinski 12y agoPython 3.4 has enums, if that's what you meant: https://docs.python.org/3/library/enum.html https://docs.python.org/3/library/enum.html
- colanderman 12y agoBut that's not a problem with JSON-the-serialization; that just means JSON begs to be extended with a rich schema definition language. It's kind of like saying "language X sucks because it doesn't have an automatic build tool; use language Y instead". You just need a build tool for X, not a new language.
- PaulFreund 12y agohttp://json-schema.org/ http://json-schema.org/