[英]Remove object with given property from JSON using regex
鉴于我有一个代表JSON对象的字符串。 它可能是无效的 ,因为可能有一些params将被另一个系统替换(例如%param%)。 我需要使用正则表达式删除已知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 ”prop,这意味着应删除此对象(但仅当值等于'true'时)。 结果我应该收到:
{
"someTopLevelProp": "value",
"arrayOfData": [
{
"absolutelyAnotherObject": %paramValue%
},
{
"firstPropIAlwaysKnow": "value",
"dontCareProp": "value",
"dontCareProp2": 2,
"flagWhichShouldIUse": false,
"somethingAtTheEnd": "value"
}
]
}
我对正则表达式的了解不够强,所以请求社区的帮助。
PS请不要提到用正则表达式解析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*{/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.