Skip to content

Commit

Permalink
jsonld serialision: serialize lists alphabetically by schema:name/@id…
Browse files Browse the repository at this point in the history
…/schema:identifier if schema:position is not used (#26)

it still need to be investigated whether this may conflict with actual rdf lists (rdf:first, rdf:next), for which support is currently not implemented (#22)
  • Loading branch information
proycon committed Sep 12, 2022
1 parent 515d7d8 commit 240349e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion codemeta/parsers/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def parse_python(g: Graph, res: Union[URIRef, BNode], packagename: str, crosswal

#pylint: disable=W0621
def add_dependency(g: Graph, res: Union[URIRef, BNode], value: str, args: AttribDict):
for dependency in splitdependencies(value):
for dependency in sorted(splitdependencies(value)):
if 'extra ==' in dependency and args.no_extras:
continue
dependency, depversion = parsedependency(dependency.strip())
Expand Down
20 changes: 18 additions & 2 deletions codemeta/serializers/jsonld.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,32 @@ def remove_blank_ids(data):
else:
return data

def alt_sort_key(data) -> str:
if isinstance(data, dict):
if 'name' in data:
return data['name']
if '@id' in data:
return data['@id']
if 'identifier' in data:
return data['identifier']
elif isinstance(data, str):
return data
return "~" #just a high alphanumeric character so it ends up after normal (ascii) stuff


def sort_by_position(data):
"""If list items have a position (schema:position) index, make sure to use it for sorting"""
"""If list items have a position (schema:position) index, make sure to use it for sorting. If not, sort alphabetically of name of id"""
if isinstance(data, (list, tuple)):
if any( isinstance(x, dict) and 'position' in x for x in data ):
try:
return list(sorted( ( sort_by_position(x) for x in data) , key=lambda x: x['position'] if isinstance(x, dict) and 'position' in x else 99999999 ) )
except TypeError: #in rare cases this might fail because of some inconsistency, return unsorted then
return [ sort_by_position(x) for x in data ]
else:
return [ sort_by_position(x) for x in data ]
try:
return list(sorted( ( sort_by_position(x) for x in data) , key=lambda x: alt_sort_key(x) ) )
except TypeError: #in rare cases this might fail because of some inconsistency, return unsorted then
return [ sort_by_position(x) for x in data ]
elif isinstance(data, dict):
for key, value in data.items():
data[key] = sort_by_position(value)
Expand Down

0 comments on commit 240349e

Please sign in to comment.