Change JSON schema from CMS (content + type of schema)

Hello everyone,

So I learnt here how to do a dynamic schema:

But it was not fully dynamic because it only worked when the type of item in the CMS does not change. If you wanted to have both video and article, or articles of different breadcrumb levels in the same collection, you’ll need some javascript.

So this is how you can change the JSON schema according to a CMS field.

For this example, I’m using a breadcrumb schema but it can also be used to switched from video schema to article schema for example.

First you’ll need a dropdown CMS field to use as reference.
In my example, I created a “level” field:
image

Than you need to create a schema for each type of CMS item you have.
I use this schema generator. It does the job really well.

Finally, you need to add a script wich takes your dropdown field and provides a schema depending on which option is selected.
And here is where the magic happens:

<script>
switch (ADD DROPDOWN FIELD HERE) {
    case OPTION A:
        var schema = {
ENTER YOUR FIRST SCHEMA HERE
            }
        break;
    case OPTION B :
        var schema = {
ENTER YOUR SECOND SCHEMA HERE
}
        break;
    default:
        var schema = {};
        break;
}
var script = document.createElement('script');
script.type = "application/ld+json";
script.text = JSON.stringify(schema);
document.querySelector('body').appendChild(script);

</script>

OPTION A and OPTION B are placeholders for the options of your dropdown field.

It should look somethink like this at the top of your script:
image

And here at the bottom:
image

Now if you go live, you should see that your items have different schemas depending on their type! You can verify with this validation tool.

Thanks to @Evan1 for the inspiration and @Baptiste_MARTY for the help in writing the code. :smiley:

I hope it might help some of you,
Have a great day,
Joachim

1 Like

Great work @Joachim_B I’m going to spend a bit of time going through this.

1 Like