简体   繁体   中英

Build a JSON dynamically with data stored in an array

I need to build a JSON dynamically.

The JSON works if it is not dynamic.

Here is a working example but the "@id" and "name" are not dynamic :

var el_2 = document.createElement('script');
el_2.type = 'application/ld+json';

el_2.text = JSON.stringify({
  "@context": "http://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [{
    "@type": "ListItem",
    "position": 1,
    "item": {
      "@id": "https://example.com/",
      "name": "Home",
    }
  }, {
    "@type": "ListItem",
    "position": 2,
    "item": {
      "@id": "https://example.com/text_1",
      "name": "Text_1",
    }
  }, {
    "@type": "ListItem",
    "position": 3,
    "item": {
      "name": "Text_2",
    }
  }
  }]
});

document.querySelector('head').appendChild(el_2);

I need to make it dynamic.

I use jQuery's each() function to loop through each element of the breadcrumb.

Then, I push the element into an array:

var array_breadcrumb_text = [];
$('.region-breadcrumb .breadcrumb li').each(function(index, value) {
  array_breadcrumb_text.push($(this).find("a").attr('href') + ' : ' + $(this).text());
  // output of links and text is  correct
  console.log(array_breadcrumb_text[index]);
});

I don't know how to use this array in order to build the JSON.

Generally, I use a foreach loop but since I am inside of the JSON.stringify() , I can't use a foreach loop, because I have a syntax issue.

Here is the breadcrumb HTML structure

<ol class="breadcrumb">
          <li>
                  <a href="/">Home</a>
          </li>
          <li>
                  <a href="/text_1">Text_1</a>
          </li>
          <li class="active">
                  Text_2
          </li>
 </ol>

I would build out a function something like:

function createListItem(el, index) {
    var $el = $(el);
    var data = { 
        "@type": "ListItem",
        "position": index,
        "item": {}
    };

    data.item['@id'] = $el.find("a").attr('href');
    data.item.name = $el.text();
    // add image etc.

    return data;
}

This builds out the ListItem parts of your data structure. You can build it like:

var array_breadcrumb_items = $('.region-breadcrumb .breadcrumb li').map(createListItem);

Once that's sorted you can:

var result = JSON.stringify({
  "@context": "http://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": array_breadcrumb_items
});

Essentially the easiest way to break up a JSON structure is to break it down into the repeatable parts, assemble them and then pass the result through the JSON.stringify as late as possible.

I finally got enough information to realise you CAN do what you are trying to do.

So I assume you want this:

 var el_2 = document.createElement('script'); el_2.type = 'application/ld+json'; var bread = { "@context": "http://schema.org", "@type": "BreadcrumbList", "itemListElement": [] } $('.breadcrumb li').each(function(index) { var item = {} var href = $(this).find("a").attr('href'); if (href) item["@id"] = href // OR location.protocol+"//"+location.host+href; item["name"] = $.trim($(this).text()); bread.itemListElement.push({ "@type": "ListItem", "position": index + 1, item }) }); el_2.text = JSON.stringify(bread); console.log(JSON.stringify(bread,null,2)) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol class="breadcrumb"> <li> <a href="/">Home</a> </li> <li> <a href="/text_1">Text_1</a> </li> <li class="active"> Text_2 </li> </ol> 

    <script>

    var bread = {
      "@context": "",
      "@type": "BreadcrumbList",
      "itemListElement": []
    }
    
    $(document).ready(function () {
        
        var counter = 1;
        
        $('li[class*="breadcrumb-item"]').each(function(i,j){
         var href = $(this).find('a:first').attr('href');
         if (!href) href = location.href;
          bread.itemListElement.push({
            "@type": "ListItem",
            "position": counter,
            "item": href,
            "name": $.trim($(j).text())
          })
        
        counter++;
        });
        var jsonStr = JSON.stringify(bread);
        $('#dynamicJSONLD').append(jsonStr);
    });
    
    </script>   
    <script id="dynamicJSONLD" type="application/ld+json"></script>

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