javascript - 如何将 javascript 对象格式化为模式数据的 JSON 对象?

标签 javascript jquery arrays javascript-objects

我在下面提到了动态 js 对象形式,我尝试将其转换为模式数据并添加到网页的 head 标记中以用于 SEO 目的。 不确定这怎么可能,因为我是这方面的新员工。

我的 JS 函数:

function populateJsonLDScript(data) {
    if (typeof (data) != "undefined" && data  != null) {
        var finalSchemaObj = {};
        var tempSchemaItems = [];
        for (var i = 0; i < data.length; i++) {
            var tempSchemaData = {};
            tempSchemaData["@type"] = "ListItem";
            tempSchemaData["position"] = data[i].DisplayOrder;
            tempSchemaData["item"] = {
                "@id": data[i].CanonicalURL,
                "name": data[i].Name
            };
            tempSchemaItems.push(tempSchemaData);
        }

        for (var i = 0; i < tempSchemaItems.length; ++i) {
            finalSchemaObj[i] = tempSchemaItems[i];
        }

        var scriptSchema = document.createElement('script');
        scriptSchema.type = 'application/ld+json';
        scriptSchema.text = JSON.stringify({
            "@context": "http://schema.org",
            "@type": "BreadcrumbList",
            "itemListElement": [finalSchemaObj]
        });
        if ($('head script[type="application/ld+json"]').length > 0) {
            $('head script[type="application/ld+json"]').remove();
            $("head").append(scriptSchema);
        } else {
            $("head").append(scriptSchema);
        }
    }
}

输出

{
    "@context": "http://schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [{
        "0": {
            "@type": "ListItem",
            "position": 0,
            "item": {
                "@id": "http://example.com",
                "name": "Home"
            }
        },
        "1": {
            "@type": "ListItem",
            "position": 1,
            "item": {
                "@id": "http://example.com/jewelry",
                "name": "Jewelry"
            }
        },
        "2": {
            "@type": "ListItem",
            "position": 2,
            "item": {
                "@id": "http://example.com/jewelry/necklaces-pendants",
                "name": "Necklaces & Pendants"
            }
        }
    }]
}

但是谷歌仍然说它的格式无效。所以,我想将上面的格式格式化为 -

{"@context":"http://schema.org","@type":"BreadcrumbList","itemListElement":[
        {
            "@type":"ListItem",
             "position":0,
             "item": {
                       "@id":"http://example.com",
                       "name":"Home"
                     }
        },
        {
           "@type":"ListItem",
            "position":1,
            "item":{
                     "@id":"http://example.com/jewelry",
                     "name":"Jewelry"
                   }
        },
        {
           "@type":"ListItem",
           "position":2,
           "item":{
                   "@id":"http://example.com/jewelry/necklaces-pendants",
                   "name":"Necklaces & Pendants"
                }
        }
    ]
}

有人请帮忙如何做到这一点?

最佳答案

不要使用对象,使用数组并压入其中。像这样:

function populateJsonLDScript(data) {
  if (typeof(data) != "undefined" && data != null) {
    var finalSchemaObj = []; // <----- use array here
    var tempSchemaItems = [];
    for (var i = 0; i < data.length; i++) {
      var tempSchemaData = {};
      tempSchemaData["@type"] = "ListItem";
      tempSchemaData["position"] = data[i].DisplayOrder;
      tempSchemaData["item"] = {
        "@id": data[i].CanonicalURL,
        "name": data[i].Name
      };
      tempSchemaItems.push(tempSchemaData);
    }

    for (var i = 0; i < tempSchemaItems.length; ++i) {
      finalSchemaObj.push(tempSchemaItems[i]); // <--- push here
    }

    var scriptSchema = document.createElement('script');
    scriptSchema.type = 'application/ld+json';
    scriptSchema.text = JSON.stringify({
      "@context": "http://schema.org",
      "@type": "BreadcrumbList",
      "itemListElement": finalSchemaObj // <----- and use finalSchemaObj here
    });
    if ($('head script[type="application/ld+json"]').length > 0) {
      $('head script[type="application/ld+json"]').remove();
      $("head").append(scriptSchema);
    } else {
      $("head").append(scriptSchema);
    }
  }
}

关于javascript - 如何将 javascript 对象格式化为模式数据的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367546/

相关文章:

jquery - 谁可以排除同源政策?

数组的 c++ 大小正在使用 sizeof 更改

c - 用存储在数组中的字符替换字符串中的某些字符会插入垃圾

php - JavaScript 将 <br> 替换为\n

jquery - 如何在 jQuery 小部件中切换 console.log?

javascript - jQuery UI 可拖动和可排序不能像我想要的那样工作

jquery - 可汗学院的提示功能是如何编码的

sql - 如何在 Postgresql 中加入 array_agg 列的 View ?

javascript - 使用 <form> 绑定(bind)数组元素的两种方式

php - 在表单提交和重定向之间显示 "Please Wait"