如何在rdflib中修改JSON-LD导出结果的ID前缀?
如何替换rdflib导出JSON-LD中@id的前缀部分
问题场景
使用rdflib加载RDF文件并导出为JSON-LD时,无法替换@id字段中的file:///path/to/original/xml前缀。
原始RDF内容:
<cim:Substation rdf:ID="_1234"> <cim:IdentifiedObject.name>A substation</cim:IdentifiedObject.name> </cim:Substation>
导出后的JSON-LD(问题示例):
{ "@id": "file:///path/to/original/xml#_418866779", "@type": "cim:Substation", "cim:IdentifiedObject.name": "A substation" },
当前使用的代码:
from rdflib import Graph g = Graph( # 设置identifier或base似乎没有效果 ) g.parse('path to rdf') js = g.serialize( format="json-ld", encoding="utf-8", destination='path to json', sort_keys=True, # 输出结果可重复,很有用。 context={ 一些相关条目(rdf, cim) }, auto_compact=True, # 设置base似乎没有效果 )
解决方案
方法1:加载RDF时指定base参数
在parse阶段传入base参数,自定义资源URI的基础前缀,rdflib会直接用这个值生成@id,而非文件路径:
g.parse('path to rdf', base="http://your/custom/base/uri")
方法2:序列化JSON-LD时指定base参数
如果加载阶段未设置,可在serialize时补充base参数,覆盖默认的文件路径前缀:
js = g.serialize( format="json-ld", encoding="utf-8", destination='path to json', sort_keys=True, context={ "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "cim": "http://your/cim/namespace/uri" }, auto_compact=True, base="http://your/custom/base/uri" # 自定义前缀 )
方法3:手动替换图中所有资源的URI前缀
若上述方法不生效,可遍历图中所有三元组,批量替换旧前缀:
from rdflib import URIRef # 定义原前缀和目标前缀 old_prefix = "file:///path/to/original/xml#" new_prefix = "http://your/custom/base/uri#" # 遍历并替换所有匹配的URI for s, p, o in list(g): # 替换主语URI if isinstance(s, URIRef) and str(s).startswith(old_prefix): new_s = URIRef(str(s).replace(old_prefix, new_prefix)) g.remove((s, p, o)) g.add((new_s, p, o)) # 替换宾语URI(如果有需要) if isinstance(o, URIRef) and str(o).startswith(old_prefix): new_o = URIRef(str(o).replace(old_prefix, new_prefix)) g.remove((s, p, o)) g.add((s, p, new_o)) # 执行序列化 js = g.serialize(...)
内容的提问来源于stack exchange,提问作者Guillaume
相关产品推荐
相关产品推荐

