On this page
Random pattern reminiscent of the Matrix movie

Unable to parse JSON-LD tag and how to fix malformed JSON

Learn how to fix malformed JSON-LD tags and avoid parsing errors. Discover best practices for structuring your JSON-LD for SEO success.

JSON-LD (JavaScript Object Notation for Linked Data) is a lightweight Linked Data format that is easy for humans to read and write.

However, when JSON-LD is malformed, it can lead to parsing errors that prevent search engines and applications from correctly interpreting the data.

To address issues related to Unable to parse JSON-LD tag and fix malformed JSON, it is essential to understand the common causes and solutions for these errors.

Understanding JSON-LD malformation

Malformed JSON-LD can happen for many different types of reasons, including:

  • Incorrect syntax: missing commas, curly brackets, or square brackets can invalidate the JSON structure. This is a common cause of parsing errors, as JSON relies heavily on these characters for its syntax.
  • Extraneous characters: there might be unnecessary characters, such as semicolons or stray commas, especially at the end of the JSON-LD script.
  • Whitespace and formatting: JSON-LD should be represented as a single string without unnecessary whitespaces or new lines. If your structured data contains line breaks or spaces, it may lead to parsing issues.
  • HTML tags in JSON: when including HTML content in a JSON property value, it’s essential to escape certain characters to ensure that the JSON remains valid. The JSON specification allows for various data types, but special characters can disrupt the structure if not handled correctly.
  • Incorrect data types: ensure the values in your JSON-LD match the expected data types for each property. For example, using a string when a number is expected will cause an Incorrect value type error.
  • Invalid @context URL: If the schema @context URL is invalid or returns an error, JSON parsers will fail. Make sure the @context URL is correct and returns a valid JSON-LD context.
  • Unsupported @context: If using Schema.org, the @context URL must be valid, according to the JSON-LD @context. This is essential for defining the terms and types used in structured data markup. This context file is utilized primarily in JSON-LD to facilitate the integration of Schema.org vocabulary into web pages.
  • Encoding issues: problems with character encoding in the JSON-LD script can lead to Invalid Unicode or Bad escape sequence errors. Make sure the encoding matches what the page is served with.

[Facebook Pixel] – Unable to parse JSON-LD tag. Malformed JSON found.

When encountering an error message like Unable to parse JSON-LD tag. Malformed JSON found related to Facebook Pixel implementation typically indicates that there’s an issue with the structure or content of the JSON-LD script you’re using on your website.

Common encoding issues

Here are some common problems related to character encoding in JSON-LD schemas:

  • UTF-8 Encoding Mismatch: the most common issue arises when the JSON-LD file is not saved or interpreted using UTF-8 encoding, which is the standard encoding for JSON files.
  • Special characters: special characters that are not properly escaped can cause parsing errors. For example, if a string contains a double quote (") without being escaped, it will break the JSON structure.
  • Non-ASCII characters: including non-ASCII characters directly in the JSON-LD file without proper encoding can lead to parsing errors or incorrect display of these characters.

How to fix malformed JSON-LD

To fix malformed JSON-LD, follow these steps:

  • Validate your JSON-LD: utilize tools like the Google Schema Markup Testing Tool, Schema.org Markup Validator, or Schema.dev Structured Data Testing Tool, to identify parsing errors.
  • Check for whitespaces: review your JSON-LD code for any whitespaces, especially new lines, that might cause parsing issues.
  • Escape HTML code: ensure that all HTML entities within your JSON-LD are properly escaped, as unescaped HTML lead to parsing errors.
  • Escape special characters: ensure all special characters within strings are properly escaped. In JSON, this means using a backslash (\) before special characters like double quotes ("), backslashes (\), and control characters.

    Example JSON with the value that represents the name “élan” using its Unicode escape sequence.
    {
      "description": "This is a \"quote\" inside a string."
    }
  • Use unicode escape sequences: for non-ASCII characters, consider using Unicode escape sequences. This involves representing the character as \uXXXX, where XXXX is the hexadecimal code point of the character.

    Example JSON with unicode escape sequences
    {
      "name": "\u00E9lan"
    }
  • Remove extraneous characters: look for any unnecessary characters, such as semicolons or stray commas, especially at the end of the JSON-LD script.
  • Use script tag and its proper type: make sure the entire JSON-LD script is enclosed within <script type="application/ld+json"></script> code block.
  • Facebook Pixel implementation: if you’re using Facebook Pixel along with JSON-LD, ensure that both scripts are correctly integrated. The Facebook Pixel code and JSON-LD schema should be placed in between the opening and closing <head> tags on every page where you will be tracking website visitor actions.
  • Review the schema: make sure that your JSON-LD conforms to the expected schema. If you’re using properties that are not part of the defined schema, consider removing or correcting them.
  • Ensure UTF-8 encoding: make sure your JSON-LD file is saved with UTF-8 encoding. Most text editors and IDEs allow you to choose the encoding when saving a file. For example, in Visual Studio Code, you can click on the Encoding label at the bottom right corner of the window and select Save with Encoding, then UTF-8.

How do we create JSON?

Creating JSON is typically done by concatenating fragments of a string or generating from objects.

However, generating JSON from objects is the safest way to ensure data integrity and prevent errors. When generating JSON from objects, you can use libraries and frameworks that provide built-in support for JSON serialization and deserialization.

JSON-generated objects adhere to a strict structure defined by the JSON specification (RFC 8259). This ensures that only valid data types are included – strings, numbers, arrays, and nested objects – thereby preventing unexpected data formats that could lead to errors or vulnerabilities.

Creating JSON string in JavaScript

To create a JSON string in JavaScript, you can use the built-in JSON.stringify() method.

Here is an example:

Creating JSON from objects using JavaScript
const obj = {
    name: "Adam",
    age: 40,
    married: true,
    children: ["Anna", "Ella"],
    image: escapeHtml('<img src="example.png" alt="Adam">')
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);

In this example, the obj object is converted into a JSON string, which will look like this:

{"name":"Adam","age":40,"married":true,"children":["Anna","Ella"]}
Escaping HTML using JavaScript
const escapeEntityMap = {
  '"': '"',
  '&': '&',
  '\'': ''',
  '/': '/',
  '<': '<',
  '=': '=',
  '>': '>',
  '`': '`'
};

function escapeHtml(str) {
  const fromEntityMap = (s) => {
    return escapeEntityMap[s];
  };

  return String(str).replace(/[&<>"'`=/]/g, fromEntityMap);
}

Creating JSON string in PHP

To create a JSON string in PHP, you can use the built-in json_encode method.

Here is an example of the BlogPosting schema generated when WordPress is used:

Creating JSON from objects using PHP
global $wp, $post;

function format_date_time($date, $time = null)
{

  $formated = '';
  $timezone = get_option('timezone_string');

  if ($timezone) {
    date_default_timezone_set($timezone);
  }

  if ($date && $time) {
    $formated = date('c', strtotime($date . ' ' . $time));
  } else {
    if ($date) {
      $formated = date('c', strtotime($date));
    }
  }

  return $formated;
}

function convert_minutes_to_iso_8601($minutes) {
  $interval = new DateInterval('PT' . $minutes . 'M');

  return $interval->format('P%yY%mM%dDT%hH%iM%sS');
}

$articleSchema = (object)[
    "@type" => "BlogPosting",
    "@id" => home_url($wp->request),
    "isPartOf" => (object)[
      "@id" => htmlspecialchars(get_permalink($post->ID))
    ],
    "author" => (object)[
      "@type" => "Person",
      "name" => esc_html(get_the_author_meta('display_name', $post->post_author)),
      "url" => get_the_author_meta('user_url', get_post_field('post_author', $post->ID))
    ],
    "creator" => esc_html(get_the_author_meta('display_name', $post->post_author)),
    "headline" => $post->post_title,
    "datePublished" => format_date_time($post->post_date),
    "dateModified" => format_date_time($post->post_modified),
    'mainEntityOfPage' => [
      '@type' => 'WebPage',
      '@id' => home_url($wp->request),
    ],
    "wordCount" => str_word_count(wp_strip_all_tags($post->post_content)),
    "commentCount" => get_comment_count($post->ID)['approved'],
    "timeRequired" => convert_minutes_to_iso_8601(get_estimated_reading_time_minutes($post)),
    "publisher" => (object)[
      "@type" => "Organization",
      "name" => get_bloginfo('name'),
      "logo" => (object)[
        "@type" => "ImageObject",
        "url" => get_bloginfo("template_url") . "/assets/images/logo-512x512.png"
      ]
    ],
    "inLanguage" => (object)[
      "@type" => "Language",
      "name" => "English"
    ],
    "keywords" => $pageKeywords,
    "thumbnailUrl" => has_post_thumbnail() ? wp_get_attachment_image_url(get_post_thumbnail_id($post->ID), 'full') : get_bloginfo("template_url") . "/assets/images/website-thumbnail.jpg"
  ];

  $jsonString = json_encode($articleSchema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Creating JSON string in C#

To create a JSON string in C#, we’ll use the Newtonsoft.Json package. This package provides functionality for working with JSON in .NET applications. You can install it via the NuGet Package Manager or by running the following command in your terminal: dotnet add package Newtonsoft.Json.

Here is an example of the Product schema:

Creating JSON from objects using C#
@using System;
@using Newtonsoft.Json;

var obj = new Dictionary<string, object>
{
    { "@context", "https://schema.org" },
    { "@type", "Product" },
    { "productID", "c42" },
    { "name", "Example Product Name" },
    { "sku", "Example SKU" },
    { "description", "Example description" },
    { "url", "URL to product" },
    { "image", "URL to the product image" },
    { "brand", new Dictionary<string, object>
        {
            { "@type", "Brand" },
            { "name", "Brand name" },
            { "logo", "URL to brand logo image" }
        }
    },
    { "offers", new List<object>
        {
            new Dictionary<string, object>
            {
                { "@type", "Offer" },
                { "price", "Price value" },
                { "priceCurrency", "USD" },
                { "itemCondition", "https://schema.org/NewCondition" },
                { "availability", "https://schema.org/InStock" },
                { "itemOffered", new Dictionary<string, object>
                    {
                        { "@context", "https://schema.org" },
                        { "@type", "IndividualProduct" },
                        { "url", "URL to the product item" },
                        { "sku", "Product item SKU" },
                        { "name", "Product item name" },
                        { "description", "Product item description" },
                        { "image", new List<object>
                            {
                                new Dictionary<string, object>
                                {
                                    { "@context", "https://schema.org" },
                                    { "@type", "ImageObject" },
                                    { "url", "Product item image URL" },
                                    { "width", 1024 },
                                    { "height", 768 }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
};

string jsonString = JsonConvert.SerializeObject(obj);
string scriptTag = String.Format("<script type=\"application/ld+json\">{0}</script>", jsonString);

@Html.Raw(scriptTag);

Conclusion

By following these guidelines, you can effectively troubleshoot and resolve issues related to malformed JSON-LD, ensuring that your structured data is correctly parsed by search engines and other tools.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Is your site slow?

Discover performance bottlenecks to provide a better customer experience and meet your company’s revenue targets.

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)