简体   繁体   中英

Generate structured data with JavaScript

We need to write a script to create a JSON-LD script for structured Data for a Component in JSP let say FAQ component, we have written script to generate JSON LD for Structured data,

faq.jsp:

<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "type": "FAQPage",
    "mainEntity": [
    <c:forEach var='questionItem' items='${faq.faqQuestionList}' varStatus='itemsLoopSchema'>
    {
    <c:set var="trimmedAnswer" value="${fn:trim(questionItem.answer)}" />
    "@type": "Question",
    "name": "${questionItem.question}",
    "acceptedAnswer": {
    "@type": "Answer",
    "text": "${fn:escapeXml(trimmedAnswer)}"
    }
    <c:choose>
        <c:when test="${itemsLoopSchema.last}">
            }
        </c:when>
        <c:otherwise>
            },
        </c:otherwise>
    </c:choose>
</c:forEach>
    ]
}
</script>

Now when this JSP Component included Multiple time the script will run multiple time and create multiple JSON

Instead I want to load all the multiple FAQ component and then create JSON (or run script only once). A single JSON LD where all the details will be there for multiple faq.jsp

*Restricting Script to run once and get the data of all the page DOM in JSON for SEO purpose in JSP

I know this may not be the answer you're looking for but having multiple json+ld blocks on the same page is perfectly valid, even if they're of the same type.

Additionally, I would recommend inlining the structured data into the FAQ markup you're outputting using microformats (using itemscope , itemprop , and itemtype attributes).

Some ideas:

  1. Add a Sling Model in the head of your page. query all FAQ components and generate the JSON+LD data. Sling Model just outputs the string

  2. Create a FAQ Container where you drop each FAQ component. FAQWrapper Sling Model generates the JSON+LD just as above

Also, some recommendations:

  1. Do the JSON generation in java, not in the JSP itself.
  2. Look for a java library that generates the schema for you, otherwise is easy to make mistakes and generating invalid data. We implemented our own solution based on Lombok SuperBuilder, Delegate, and Jackson and it was a lot of work
  3. Although google recommends using JSON+LD, I've seen websites using microformats and it works just fine, so consider Raphael's suggestion.

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