简体   繁体   中英

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!

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM