如果它没有ID,有没有办法通过JavaScript访问JSON-LD?

Pra*_*han 7 javascript json google-apps-script json-ld

我试图访问我收到的eventbrite电子邮件中的内容,但html代码没有与JSON-LD脚本关联的ID.那么有没有办法仍然访问这些数据?如果是这样,怎么样?

是否可以将临时ID附加到JSON-LD脚本标记,以便我可以访问数据?如果是这样,怎么样?

Mar*_*ler 17

您可以使用所有JSON-LD块

 document.querySelectorAll('script[type="application/ld+json"]');
Run Code Online (Sandbox Code Playgroud)

或者只是第一个

document.querySelector('script[type="application/ld+json"]');
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:

var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
document.getElementById('result').innerText = jsonld.endDate;
Run Code Online (Sandbox Code Playgroud)
<html>
  <head>
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "Event",
        "name": "A random event",
        "startDate": "2013-09-14T21:30",
        "endDate": "2013-09-14T21:30"
      }
    </script>
  </head>
  <body>
    <p>The end date is: <strong id="result"></strong></p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)