Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 560
Aleksandra Chuprova Avatar asked Mar 25 '26 11:03

Aleksandra Chuprova


1 Answers

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

like image 85
Ismail RBOUH Avatar answered Mar 26 '26 23:03

Ismail RBOUH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!