JSON 在 javascript 中解析 json-ld

JSON parsing in javascript for json-ld

正在尝试从 json-ld

解析 JSON

下面是JSON:

{
  "@context": "http://json-ld.org/contexts/person.jsonld",
  "@id": "http://dbpedia.org/resource/John_Lennon",
  "name": "John Lennon",
  "born": "1940-10-09",
  "spouse": "http://dbpedia.org/resource/Cynthia_Lennon"
}

所以我正在尝试这样做:

var jsonData= {
  "@context": "http://json-ld.org/contexts/person.jsonld",
  "@id": "http://dbpedia.org/resource/John_Lennon",
  "name": "John Lennon",
  "born": "1940-10-09",
  "spouse": "http://dbpedia.org/resource/Cynthia_Lennon"
};

console.log(jsonData.@context);// Error:Uncaught SyntaxError: Invalid or unexpected token
console.log(jsonData.name);// John Lenon

那我该如何解析@context?请推荐。

console.log(jsonData['@context']);

有关 Javascript 的更多信息 Property accessors:圆点表示法和括号表示法。

请使用

console.log(jsonData['@id']).

不仅如此,您还不能使用以@开头的Javascript变量名。

javascript变量命名约定可以参考这篇。 https://mathiasbynens.be/notes/javascript-identifiers

您可以将其解析为:

var jsonData = {
    "@context": "http://json-ld.org/contexts/person.jsonld",
    "@id": "http://dbpedia.org/resource/John_Lennon",
    "name": "John Lennon",
    "born": "1940-10-09",
    "spouse": "http://dbpedia.org/resource/Cynthia_Lennon"
};

console.log(jsonData['@context']);`