KJ3*_*KJ3 7 javascript validation json mongodb
我想检查用户输入的文本是否是有效的JSON.我知道我可以使用这样的东西轻松地做到这一点:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是与来自蒙戈,它被包裹在JSON ObjectId,ISODate即:
{
"_id" : ObjectId("5733b42c66beadec3cbcb9a4"),
"date" : ISODate("2016-05-11T22:37:32.341Z"),
"name" : "KJ"
}
Run Code Online (Sandbox Code Playgroud)
这不是有效的JSON.如何在允许上述内容的同时验证JSON?
你可以用字符串替换裸函数调用,像这样
function IsJsonLikeString(str) {
str = str.replace(/(\w+)\("([^"]+)"\)/g, '"$1(\"$2\")"');
try {
JSON.parse(str);
} ...
Run Code Online (Sandbox Code Playgroud)
来自https://regex101.com/r/fW7iH4/#javascript的解释:
/(\w+)\("([^"]+)"\)/g
1st Capturing group (\w+)
\w+ match any word character [a-zA-Z0-9_]
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\( matches the character ( literally
" matches the characters " literally
2nd Capturing group ([^"]+)
[^"]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
" a single character in the list " literally (case sensitive)
" matches the characters " literally
\) matches the character ) literally
g modifier: global. All matches (don't return on first match)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
937 次 |
| 最近记录: |