Conditional Embed - How to use JS to stop JSON script running

Hi guys

I hope somebody can help me - i’m trying to implement some structured data in the form of a short JSON-LD script that contains tagged collection list fields. This works great where the fields have a value, but for pages that don’t the script still runs in the background with empty fields. The issue being that Google can see the incomplete schema and this can down value my site for SEO.

I’ve tried to create small addition to the script to check if the collection field is empty, and if so it should not execute the schema.

this does not work - i had it working earlier but with an error . I need a snippet of code I can use with my schema that does not throw an error.

Obv don’t know enough about JS to do it myself…Any help would be much appreciated!

Hi John,
I am not sure if this is the problem, since I am not a JS expert, but is having a <script> tag inside a <script> tag something that should work?

thanks for replying - yes I believe you are right, and I have tried by removing the second but I then don’t know how to change the script type - it needs to be classified as JSON-LD or it seems to treat the schema part as normal JS.

OK i think i did it - I started from scratch. Using the IF statement to determine if FAQ is defined or null. If null, then it just sets a dummy variable to true. If defined then it runs the schema which is nested preceded with “data=” as the equivalent to entering the script tag. Only issue now is getting the JSON recognised - need to assign data type as JSON-LD.

Hi John, did you work out how to assign the data type as JSON-LD?