【发布时间】:2019-11-13 11:11:07
【问题描述】:
我希望能够让用户能够指定路径和有效的正则表达式,并基于此返回过滤后的 JSON。
我想我几乎有了我的解决方案,只是我不知道如何动态获取路径的结果。这是我的代码:
function getResult(jsonObject, pathText, regexToCheck) {
var pathArr = pathText.split(".")
var jsonPath = ''
console.log('start...')
for(var key in pathArr){
var addPath = "['"+ pathArr[key] +"']"
jsonPath += addPath
}
result = jsonObject[jsonPath]
return result.match(new RegExp(regexToCheck, 'g'), match)
}
function filterBy (json, path, regexToCheck){
var parseJSON = json
var filterResult = [];
for(var obj in parseJSON){
var result = getResult(parseJSON[obj], path, regexToCheck)
console.log(result)
if (result == true){
filteredResult.push(parseJSON[obj])
}
}
return filterResult
}
filterBy(json, path, regexToCheck)
我希望前面提到的是让用户指定一个路径和正则表达式,如var path = 'configurationId.id' 和var regexToCheck = /^[4]/,并给出下面的测试数据
var json = [{
"configurationId": {
"id": "7000",
"displayName": "7000",
"uri": "/configuration/users/7000"
},
"licenseProperties": {
"hasClientAccess": true
},
"roles": {
"actualValue": [{
"id": "Agent",
"displayName": "Agent",
"uri": "/configuration/roles/Agent"
},
{
"id": "SMS",
"displayName": "SMS",
"uri": "/configuration/roles/SMS"
}
]
}
}, {
"configurationId": {
"id": "7001",
"displayName": "7001",
"uri": "/configuration/users/7001"
},
"licenseProperties": {
"hasClientAccess": true
},
"roles": {
"actualValue": [{
"id": "Agent",
"displayName": "Agent",
"uri": "/configuration/roles/Agent"
},
{
"id": "SMS",
"displayName": "SMS",
"uri": "/configuration/roles/SMS"
}
]
}
}, {
"configurationId": {
"id": "7002",
"displayName": "7002",
"uri": "/configuration/users/7002"
},
"licenseProperties": {
"hasClientAccess": true
},
"roles": {
"actualValue": [{
"id": "Agent",
"displayName": "Agent",
"uri": "/configuration/roles/Agent"
},
{
"id": "SMS",
"displayName": "SMS",
"uri": "/configuration/roles/SMS"
}
]
}
}, {
"configurationId": {
"id": "4003",
"displayName": "4003",
"uri": "/configuration/users/4003"
},
"licenseProperties": {
"hasClientAccess": true
},
"roles": {
"actualValue": [{
"id": "Agent",
"displayName": "Agent",
"uri": "/configuration/roles/Agent"
},
{
"id": "SMS",
"displayName": "SMS",
"uri": "/configuration/roles/SMS"
}
]
}
}];
返回结果,
{
"configurationId": {
"id": "4003",
"displayName": "4003",
"uri": "/configuration/users/4003"
},
"licenseProperties": {
"hasClientAccess": true
},
"roles": {
"actualValue": [{
"id": "Agent",
"displayName": "Agent",
"uri": "/configuration/roles/Agent"
},
{
"id": "SMS",
"displayName": "SMS",
"uri": "/configuration/roles/SMS"
}
]
}
因为我的正则表达式只是检查 id 是否以 4 开头。同样重要的是要注意这必须与嵌套的 JSON 一起使用,因此是路径规范。所以,重新迭代我的代码失败的地方基本上在这里:result = jsonObject[jsonPath]
【问题讨论】:
-
试试 GSON github.com/google/gson
-
@yoga 用于 Java 而不是 Javascript。此外,如果可能的话,id 喜欢保持纯 JS 而不需要依赖
标签: javascript json regex