Insert Variable from jQuery Into JSON Schema Markup

Tags: , , ,



I’m trying to get the meta description and copy the content of it into some JSON schema markup. But I’m not sure how to get it to pass the variable into to the JSON structure correctly.

Here’s what I was thinking:

<script>
      const desc = $('meta[name=description]').attr("content");
    </script>
    <script type='application/ld+json'>
      {
        "@context": "http://www.schema.org",
        "@type": "LocalBusiness",
        "name": "BizName",
        "telephone": "+1234567890",
        "description": "'+desc+'",
        ....
      }
    </script>

I understand that it’s not going to fully pass the desc variable directly into the JSON markup since it’s within separate script tags. I’m just not sure how to combine the two so that it works correctly. Hope that makes sense and open to any suggestions.

Answer

Build the schema first then inject it in.

<script>
      const desc = $('meta[name=description]').attr("content").toString();
      var schema = {
        "@context": "http://www.schema.org",
        "@type": "LocalBusiness",
        "name": "BizName",
        "telephone": "+1234567890",
        "description": desc,
        ....
      }      
      var script = document.createElement('script');
        script.type = "application/ld+json";
        script.text = JSON.stringify(schema);

        document.querySelector('body').appendChild(script);
</script>


Source: stackoverflow