【问题标题】:What is the best way to get a property value from all json-ld objects on a page?从页面上的所有 json-ld 对象获取属性值的最佳方法是什么?
【发布时间】:2016-11-18 22:02:39
【问题描述】:

我正在尝试从产品结果页面中提取所有 mpn 值,其中数据以 JSON-LD 格式存储。获取前 10 个值,这是最理想的方法吗?

(function(){
var mpns=   document.querySelectorAll('script[type="application/ld+json"]');
var x = [];
mpns.forEach(
    function(value){
        var a = JSON.parse(value.innerText).mpn;
        x.push(a);
    }
);
return x.slice(0,10);
})();


<script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "Executive Anvil",
  "image": "http://www.example.com/anvil_executive.jpg",
  "description": "Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height.",
  "mpn": "925872",
  "brand": {
    "@type": "Thing",
    "name": "ACME"
   }
  }
 }
</script>

【问题讨论】:

    标签: javascript json-ld


    【解决方案1】:

    不,这不是好方法。因为如果mpns array iength 以 1000000 为单位,那么如果你只想要前 10 个元素,那么 push 的含义是什么。

    所以试试 for 循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多