假设我有一个代表 JSON 对象的字符串。它可能是无效,因为可能有一些参数将被另一个系统替换(例如 %param%)。我需要使用 regex 删除已知 propertyName 等于“true”的所有对象。
{
"someTopLevelProp": "value",
"arrayOfData": [
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": $paramValue$,
"dontCareProp2": 2,
"flagWhichShouldIUse": true,
"somethingAtTheEnd": "value"
},
{
"absolutelyAnotherObject": %paramValue%
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": false,
"somethingAtTheEnd": "value"
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": true,
"somethingAtTheEnd": "value"
}
]
}
在上面的例子中,我总是有“firstPropIAlwaysKnow”,这意味着对象可以包含我需要的标志。之后可能还有其他属性。但这里最重要的是“flagWhichShouldIUse”属性,这意味着应该删除该对象(但仅在值等于“true”的情况下)。结果我应该收到:
{
"someTopLevelProp": "value",
"arrayOfData": [
{
"absolutelyAnotherObject": %paramValue%
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": false,
"somethingAtTheEnd": "value"
}
]
}
我在正则表达式方面的知识还不够丰富,因此请向社区寻求帮助。
附言请不要提及使用正则表达式解析 JSON 是疯狂\不正确\坏主意 - 确保我知道这一点。
回答: 现在我有可以执行该操作的正则表达式。感谢所有试图在这里提供帮助的人。也许它对某人有用。
/{\s+?"firstPropIAlwaysKnow": "value"[^{}]+?(?:\{[^}]*\}[^}]+?)*[^}]+?"flagWhichShouldIUse": true[^}]+?},?/gi
最佳答案
你真的不能只用正则表达式来做到这一点。这样的事情可能会起作用:
let filtered = jsonstring
// split into the individual 'objects'
// might need to modify this depending on formatting. You
// could use something like /},\s*{/ to split the string,
// but couldn't re-join with same formatting
.split('},{')
// filter for only the strings with the relevant property
// set to false
.filter(s => s.match(/"flagWhichShouldIUse":\s*false/) // again, may need to change
// put humpty-dumpty back together again
.join('},{');
确切的拆分方法在很大程度上取决于您的 JSON 结构,这并非万无一失。它不能正确处理嵌套。如果您的 JSON 打印精美,您可以使用制表符/空格字符的数量作为拆分器的一部分:例如,这只会拆分一个制表符:/\n\t},\s*{/
关于javascript - 使用正则表达式从 JSON 中删除具有给定属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635406/