正则表达式模式去除一些无效的 JSON 元素
感谢您的阅读!
我正在尝试以如下格式解析 JSON 提要:
(bpjc{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}})
在解析 JSON 时和使用 JSON 验证器,我认为 (bpjc
和结束的 )
不是有效的 JSONObject
,因此需要将它们从 feed 中删除。
因此,我编写了如下正则表达式:
String regex = "\\(bpjc.*\\)";
String input = "(bpjc{abcd})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
System.out.println(matcher.matches());
输出为 true
但如何提取 {abcd}
?
我指的是 正则表达式教程 ,但我不知道哪种模式适用于我的情况。
Thanks for reading!
I am trying to parse a JSON feed in a format like this:
(bpjc{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}})
I got error while parsing JSON and after using JSON Validator, I figured that (bpjc
and the closing )
is not a valid JSONObject
and so need to strip them out from the feed.
So, I wrote a regular expression as below:
String regex = "\\(bpjc.*\\)";
String input = "(bpjc{abcd})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
System.out.println(matcher.matches());
The output is true
but how do I extract {abcd}
?
I am referring the Regular Expressions tutorial but I don't know which pattern applies to my case.
EDIT: Adding the JSON parsing tutorial that I referred. I found it well-explained.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎得到了格式不正确的 JSONP 结果。如果您知道字符始终会出现在之前和之后,只需执行一个子字符串:
json = json.substring(5, json.length-1)
It seems you are getting an incorrectly formatted JSONP result. If you know the characters are always going to be there before and after, just do a substring:
json = json.substring(5, json.length-1)