application/ld+json and javascript data exchange

拜拜、爱过 提交于 2021-01-27 17:26:53

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/38437546/application-ldjson-and-javascript-data-exchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!