Search code examples
javascriptschemabloggerjson-ld

Using structured data markup javascript


In structured data markup, I want to insert publish date with java script.is there a way to do this?

example schema;

<script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "NewsArticle",
      "headline": "Article headline",
      "image": [
        "https://example.com/photos/1x1/photo.jpg",
        "https://example.com/photos/4x3/photo.jpg",
        "https://example.com/photos/16x9/photo.jpg"
       ],
      "datePublished": "+ date variable +",
      
      "author": [{
          "@type": "Person",
          "name": "Jane Doe",
          "url": "http://example.com/profile/janedoe123"
        },{
          "@type": "Person",
          "name": "John Doe",
          "url": "http://example.com/profile/johndoe123"
      }]
    }
    </script>

I have to take the date inside the time tag on the page and put it in the schema with javascript.

<time datetime="2021-02-24T12:11:00+03:00">2021-02-24T12:11:00+03:00</time>

Solution

  • I removed the datePublished because it's not valid markup if there are JS variables, we should add it completely using JS, this is valid even if Javascript is disabled.

    <script id='structured-data' type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "NewsArticle",
      "headline": "Article headline",
      "image": ["https://example.com/photos/1x1/photo.jpg", "https://example.com/photos/4x3/photo.jpg", "https://example.com/photos/16x9/photo.jpg"],
      "author": [{
          "@type": "Person",
          "name": "Jane Doe",
          "url": "http://example.com/profile/janedoe123"
        },{
          "@type": "Person",
          "name": "John Doe",
          "url": "http://example.com/profile/johndoe123"
        }]
    }
    </script>
    

    and to add datePublished you can use this

    let timeValue = document.querySelector('time').dateTime;
    let structuredData = document.getElementById('structured-data');
    let parsedSD = JSON.parse(structuredData.innerText);
    parsedSD.datePublished = timeValue;
    structuredData.innerText = JSON.stringify(parsedSD)