Reemwal
Reemwal

Reputation: 11

Can I use variables in JSON-LD?

I'm trying to implement Schema.org in a FAQ page, but it seems repetitive to re-write all the questions and answers in the schema.

So I was wondering if I could call a variable or a class in my JSON-LD to retrieve the questions and answers from the body.

Something like the code below:

<head>
<script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      "url": "https://www.example.com",
      "mainEntity": [{
        "@type": "Question",
        "name": {{question}},
        "acceptedAnswer": {
          "@type": "Answer",
          "text": {{answer}}
        }
      }]
      }
    </script>
</head>
<body>
    <h3 class="question">This is question number one?</h3>
    <p id="answer"> This is the answer to Q1.</p>

    <h3 class="question">This is question number 2?</h3>
    <p class="answer">This is the answer to Q2.</p>
</body>

Upvotes: 1

Views: 1682

Answers (1)

unor
unor

Reputation: 96607

No, JSON-LD doesn’t allow this.

If you don’t want to repeat your content, you can use Microdata or RDFa. With these syntaxes, you add attributes to your existing HTML elements (details).

With RDFa, it could look like:

<body typeof="schema:FAQPage">

  <link property="schema:url" href="https://www.example.com/" />

  <article property="schema:mainEntity" typeof="schema:Question">

    <h3 property="schema:name">This is question number one?</h3>

    <div property="schema:acceptedAnswer" typeof="schema:Answer">
      <p property="schema:text">This is the answer to Q1.</p>
    </div>

  </article>

</body>

(by using RDFa’s vocab attribute e.g. on the html element, you could omit the schema: prefix; by using RDFa’s prefix attribute, you could define a different, e.g. shorter, prefix)

Upvotes: 2

Related Questions