application/ld+json和javascript数据交换

application/ld+json and javascript data exchange

我有一些 jQuery 代码可以构造一个名为 myList[] 的数组。这个数组出现在控制台中是这样的:["2 items", "3items", "so on"],所以这部分很顺利。

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

我需要将 myList[] 传递给 application/ld+json 喜欢的

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

..

如何将值从 javascript 传递到 application/ld+json?提前致谢!

请试试这个:

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

然后:

var myList = [];

function buildMyList() {
    return ["2 items", "3items", "so on"];
}

$("#myJSONID").text(function() {
    return JSON.stringify({
        "@context": "http://schema.org/",
        "@type": "Recipe",
        "recipeIngredient": buildMyList()
    });
});

或:

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

演示: https://jsfiddle.net/iRbouh/9po7dtg4/

注意:请确保将 recipeIngredients 更改为 recipeIngredient,单数。 (谢谢@AlexKudryashev)。