Search code examples
javascriptjqueryjson-ld

application/ld+json and javascript data exchange


I have some jQuery code which constructs an array called myList[]. This array appears in the console like this: ["2 items", "3items", "so on"], so this part goes well.

<script type="text/javascript">
var myList = [];
function buld myList(){
...
}

I need to pass myList[] to the application/ld+json like

<script type="application/ld+json">
{
    "@context": "http://schema.org/",
    "@type": "Recipe",
    "recipeIngredients": myList, //this one doesn't work 
}

..

How can I pass the values from javascript to the application/ld+json? Thanks in advance!


Solution

  • Please try this:

    <script id="myJSONID" type="application/ld+json"></script>
    

    Then:

    var myList = [];
    
    function buildMyList() {
        return ["2 items", "3items", "so on"];
    }
    
    $("#myJSONID").text(function() {
        return JSON.stringify({
            "@context": "http://schema.org/",
            "@type": "Recipe",
            "recipeIngredient": buildMyList()
        });
    });
    

    Or:

    <script type="text/javascript">
      var myList = [];    
      function buildMyList() {
          return ["2 items", "3items", "so on"];
      }
    
      var el = document.createElement('script');
      el.type = 'application/ld+json';
    
      el.text = JSON.stringify({
            "@context": "http://schema.org/",
            "@type": "Recipe",
            "recipeIngredient": buildMyList()
        });
    
      document.querySelector('body').appendChild(el);
    </script>
    

    Demo: https://jsfiddle.net/iRbouh/9po7dtg4/

    Note: Please make sure you change recipeIngredients to recipeIngredient, singular. (Thank you @AlexKudryashev).