我正在学习Javascipt,我想找到满足条件的JSON对象并收集它们。 *条件:@type =“产品” 我使用这段代码来解析满足条件的JSON。
var jsonArray = [];
var jsons = document.querySelectorAll('script[type="application/ld+json"]');
for(var i=0; i<jsons.length; i++){
var parsingJSON = JSON.parse(jsons[i].innerText);
var product = parsingJSON.filter(function(json) {
return json['@type'] == 'Product';
});
jsonArray.push(product);
};
问题是每个站点都有不同的 JSON 格式。有些是数组的形式,
<script type="application/ld+json">[{"@context":"https://schema.org","@type":"Product","name":...}, {"@context":"https://schema.org","@type":"BreadCrumb","name":...},...]
其他都是单个对象,
<script type="application/ld+json">{"@context":"http://schema.org","@type":"BreadcrumbList","itemListElement":...}
</script>
(In this case filter function is not working.)
当JSON形式不同时,如何找到符合条件的JSON对象并收集它们? 我需要你的帮助。预先感谢您:)
最佳答案
就您而言,您收到两种类型,
对象数组
[{"@context":"https://schema.org","@type":"Product","name":...},{"@context":"https://schema.org","@type":"BreadCrumb","name":...},...]
对象
{"@context":"http://schema.org","@type":"BreadcrumbList","itemListElement":...}
方法filter
仅适用于Array
。您不能将其用于对象。这就是您收到错误的原因...
所以在应用filter
之前,你需要检查数据是array
还是object
。
var jsonArray = [];
var jsons = document.querySelectorAll('script[type="application/ld+json"]');
for(var i=0; i<jsons.length; i++){
var parsingJSON = JSON.parse(jsons[i].innerText);
if(Array.isArray(parsingJSON)) {
var product = parsingJSON.filter(function(json) {
return json['@type'] === 'Product';
});
} else {
var product = (parsingJSON['@type'] === 'Product') ? parsingJSON : null;
}
if (product !== null) {
jsonArray.push(product);
}
};
关于javascript - 我想找到符合条件的JSON对象并收集它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897407/