首页 > 解决方案 > 使用 nodejs 解析结构化 JSON-LD 文件的问题

问题描述

我尝试使用jsonld-streaming-parser.js库用 Nodejs 解析 JSON-LD 文件。

该文件是一个结构化的 JSON-LD,所以我感兴趣的所有元素都位于的根目录下@graph

{
  "@context": {
    "@vocab": "https://www.datatourisme.gouv.fr/ontology/core#",
    "schema": "http://schema.org/",
    "bd": "http://www.bigdata.com/rdf#",
    (...)
  },
  "@graph": [{
    "@id": "https://data.datatourisme.gouv.fr/3/06a7f439-3e02-3aa2-8301-f850bb5b792f",
    "dc:date": [{
      "@value": "2013-10-30",
      "@type": "xsd:date"
    },{
      "@value": "2019-08-30",
      "@type": "xsd:date"
    }],
    "dc:identifier": "eudonet:52945",
    "@type": ["schema:Landform","NaturalHeritage","PlaceOfInterest","PointOfInterest","urn:resource"],
    "rdfs:label": {
      "@value": "L'arbre du Pied Cornier",
      "@language": "fr"
    },
    (...)
  }]
}

我可以使用以下代码解析文件:

const JsonLdParser = require('jsonld-streaming-parser').JsonLdParser;

const parser = new JsonLdParser();

const getStream = () => {
  const jsonData = 'flux-5339-201909240851.partial.jsonld';
  const stream = fs.createReadStream(jsonData, {encoding: 'utf8'});
  return stream.pipe(parser);
};

getStream()
  .on('data', (data) => {
    console.log('data = ', data);
  })
  .on('error', () => {
    console.error(error);
  })
  .on('end', () => {
    console.log('All triples were parsed!');
  });

我希望在data回调中有一个元素的全面内容,但得到了这个:

{
  "subject": {
    "value": "https://data.datatourisme.gouv.fr/3/06a7f439-3e02-3aa2-8301-f850bb5b792f"
  },
  "predicate": {
    "value": "http://purl.org/dc/elements/1.1/date"
  },
  "object": {
    "value": "2013-10-30",
    "datatype": {
      "value": "http://www.w3.org/2001/XMLSchema#date"
    },
   "language": ""
  },
  "graph": {
    "value": ""
  }
}

谢谢你的帮助!蒂埃里

标签: node.jssemantic-webjson-ld

解决方案


您正在使用的 JsonLd 流解析器库似乎仅将 JsonLd 转换为 RDF 三元组(有关详细信息,请参阅RDF 规范)。

我认为您从描述中想要的是 JsonLd 图的框架。您可以使用Node 的标准 JsonLd 解析库来实现这一点。

在您的情况下,框架应该像

{
    "@context": {
        "@vocab": "https://www.datatourisme.gouv.fr/ontology/core#",
        "schema": "http://schema.org/",
        "bd": "http://www.bigdata.com/rdf#",
        (...)
     },
     "@id": "https://data.datatourisme.gouv.fr/3/06a7f439-3e02-3aa2-8301-f850bb5b792f"
}

它应该为您提供紧凑 JsonLd 中第一项的属性。如果图表中有多个项目,您可以更改@id@type并返回与特定类型匹配的所有项目。


推荐阅读