javascript - 我想找到符合条件的JSON对象并收集它们

标签 javascript json dom

我正在学习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/

相关文章:

javascript - 遍历 JavaScript 对象的最安全方法

javascript - JS是否将参数列表视为可以关闭的范围?

json - 我如何获得在 Twitter 上发布的四方签到的位置(纬度、经度)?

javascript - 获取具有定义类型的 JSON 对象长度

innerHTML 的 javascript getElementsByName 错误

javascript - 捕获刷新并将页面更改为index.html

javascript - 为什么用#!而不是 Ajax 请求中的#?

json - 为什么 Angular Universal Server Side Rendering 在部署到 Firebase Hosting 后会出错?

javascript - Puppeteer 始终未定义,但 devtools 适用于嵌套 Node 列表

javascript - 如何在不更改 DOM 的情况下计算文本选择的高度