从页面上的所有json-ld对象获取属性值的最佳方法是什么?

时间:2016-11-18 22:02:39

标签: javascript json-ld

我正在尝试从产品结果页面中提取所有mpn值,其中数据以JSON-LD格式存储。抓住前十大价值观,这是最理想的做法吗?

(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>

1 个答案:

答案 0 :(得分:0)

不,这不是好方法。因为如果mpns数组iength是1000000,那么如果你只需要前10个元素,那么push的含义是什么。

所以请尝试循环