application/ld + json和javascript数据交换

Ale*_*ova 2 javascript jquery json-ld

我有一些jQuery代码构造一个名为的数组myList[].这个数组出现在控制台中,如下所示:["2 items", "3items", "so on"]所以这部分进展顺利.

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

我需要传递myList[]application/ld+json

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

..

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

Ism*_*OUH 8

请试试这个:

<script id="myJSONID" type="application/ld+json"></script>
Run Code Online (Sandbox Code Playgroud)

然后:

var myList = [];

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

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

要么:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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