javascript-使用jQuery解析和搜索JSON文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-使用jQuery解析和搜索JSON文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1991字,纯文字阅读大概需要3分钟。
内容图文
![javascript-使用jQuery解析和搜索JSON文件](/upload/InfoBanner/zyjiaocheng/678/17297515b2fe4ea88a6764e909efeba5.jpg)
我正在尝试编写一些代码来分析和搜索JSON文件中的行业.该代码将被添加到自动完成脚本中,并返回找到的项目(与该问题无关).我有以下JSON文件:
{
"sectors": [
{
"title": "Business, Finance & Technology",
"subsectors": [
{
"title": "Finance and insurance",
"industries": [
{
"name": "Retail banking",
"name": "Insurance",
"name": "Investment banking"
}
],
"title": "Business Services",
"industries": [
{
"name": "Accounting & Audit",
"name": "Recruitment",
"name": "Legal services"
}
]
}
],
"title": "Life & Consumer",
"subsectors": [
{
"title": "Life Sciences",
"industries": [
{
"name": "Biotechnology",
"name": "Pharmaceutical",
"name": "Medical supplies"
}
],
"title": "Healthcare",
"industries": [
{
"name": "Surgery",
"name": "Medicine",
"name": "Nursery"
}
]
}
]
}
]
}
这段代码:
var q = 'Insurance';
$.getJSON('models/industries.json', function(data) {
$.each(data, function(i, item) {
if (item.sectors.subsectors.industries.search(new RegExp(q, "i")) != -1) {
$('<li />').html(item.name).appendTo('body');
}
});
});
但是,它不起作用.
我尝试了不同的变化:
if (item.name.search(new RegExp(q, "i")) != -1) {
这引发一个错误Uncaught TypeError:无法调用未定义的方法“搜索”
有任何想法吗?
编辑:
感谢下面的@Arun P Johny,我解决了问题.我的JSON文件存在问题:每个行业,子行业和行业都需要大括号{}.我需要遍历每个子部门和部门:
var q = 'Insurance',
regex = new RegExp(q, "i");
$.getJSON('models/industries.json', function (data) {
$.each(data.sectors, function (i, sector) {
$.each(sector.subsectors, function (i, subsector) {
$.each(subsector.industries, function (i, industry) {
if (industry.name.search(regex) != -1) {
$('<li />').html(industry.name).appendTo('body');
}
})
});
});
});
解决方法:
您需要遍历扇区,子扇区和行业数组
var q = 'Insurance',
regex = new RegExp(q, "i");
$.getJSON('models/industries.json', function (data) {
$.each(data.sectors, function (i, sector) {
$.each(sector.subsectors, function (i, subsector) {
$.each(subsector.industries, function (i, industry) {
if (industry.name.search(regex) != -1) {
$('<li />').html(industry.name).appendTo('body');
}
})
});
});
});
内容总结
以上是互联网集市为您收集整理的javascript-使用jQuery解析和搜索JSON文件全部内容,希望文章能够帮你解决javascript-使用jQuery解析和搜索JSON文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。