Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to access JSON-LD via JavaScript if it doesn't have an ID?

I am trying to access the content in eventbrite emails that I receive but the html code doesn't have an ID associated to the JSON-LD script. So is there a way to still access this data? If so, how?

Is it possible to perhaps attach a temporary id to the JSON-LD script tag so that I can access the data? If so, how?

like image 324
Prachy Mohan Avatar asked Jul 27 '16 02:07

Prachy Mohan


People also ask

How do I access a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Is JSON-LD JavaScript?

JSON-LD stands for JavaScript Object Notation for Linked Data, which consists of multi-dimensional arrays (think: list of attribute-value pairs). It is an implementation format for structuring data analogous to Microdata and RDFa.

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.


1 Answers

You can get all JSON-LD blocks with

 document.querySelectorAll('script[type="application/ld+json"]');

or just the first one with

document.querySelector('script[type="application/ld+json"]');

Here's a full example:

var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
document.getElementById('result').innerText = jsonld.endDate;
<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>
like image 98
Markus Lanthaler Avatar answered Nov 15 '22 13:11

Markus Lanthaler