JSON-LD for a Node app

Has anyone successfully implemented JSON-LD with dynamic data (in my case job schema) in a nodejs app?

I've dabbled with this today and also looked at a few solutions (unsuccessfully so far with ChatGPT).

Just wondering if anyone has achieved an implementation with JSON-LD that could point me in the right direction?

Thanks.

For anyone with the same issue/implementation requirement, I managed to get this working.

  1. Create the JSON schema on the backend. I used a setvalue with data type as 'Object'.
  2. I add a var on the front end with dynamic value set as the schema from the backend.
  3. I then runJS when the var is updated (dmx-on:updated) code below:

run({runJS:{name:'processJSON',outputType:'text',function:'renderJSONLD',args:[varjsonldschema.value]}})

  1. I include a js script at the bottom of the page:
<script>
    function renderJSONLD(jsonData) {
    try {
        // Parse JSON if it comes as a string (ensure it's an object)
        const parsedData = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;

        // Convert to a JSON string for embedding
        const jsonString = JSON.stringify(parsedData);

        // Find or create the <script> tag for JSON-LD
        let scriptTag = document.getElementById('jsonld-script');
        if (!scriptTag) {
            scriptTag = document.createElement('script');
            scriptTag.type = 'application/ld+json';
            scriptTag.id = 'jsonld-script';
            document.head.appendChild(scriptTag);
        }

        // Update the <script> tag content
        scriptTag.textContent = jsonString;

        console.log('JSON-LD script tag updated successfully:', jsonString);
    } catch (error) {
        console.error('Failed to process JSON-LD:', error);
    }
}
</script>
  1. Below this I include the jsonLD script with id used in the above script:

<script type="application/ld+json" id="jsonld-script"></script>

Google correctly pics this up when testing via: https://search.google.com/test/rich-results

2 Likes

Nice work @mgaussie!
I have just done something similar for breadcrumbs on the other day, but in a very different way...

I like your version, so I will probably redo all :slight_smile:

Would you share your backend, how did you generated the json?

Gabor