布森是一种扩展的JSON格式。例如,这些文档是有效的BSON文档,但是无效的JSON文档:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"k": 10,
"dt": ISODate("2018-10-10")
},
{
"_id": ObjectId("5a934e000102030405000001"),
"k": {
"field1": "someVal",
"field2": 12.2323242
}
},
{
_id: ObjectId("5a934e000102030405000002"),
k: 7
}
][{"_id":ObjectId("5a934e000102030405000000"),"k":10,"dt":ISODate("2018-10-10")},{"_id":ObjectId("5a934e000102030405000001"),"k":{"field1":"someVal","field2":12.2323242}},{_id:ObjectId("5a934e000102030405000002"),k:7}]我最近需要一个工具来压缩或美化BSON文档。经过几次使用javascript格式化程序的尝试(美化,美化.)我最终实现了我自己的解决方案。
重要信息:
此代码的目标不是检查文档是否具有有效的BSON语法,而只是为了美化/压缩BSON文档。因此,它假定src是有效的BSON。
这是我的解决方案:
const compactMode = 0
const indentMode = 1
function indent(src) {
return write(src, indentMode)
}
function compact(src) {
return write(src, compactMode)
}
function write(src, mode) {
var result = ""
var needIndent = false
var inValue = false
var depth = 0
for (var i = 0; i < src.length; i++) {
c = src.charAt(i)
if (c === " " && !inValue || c === "\n") {
continue
}
if (needIndent && c !== "]" && c !== "}") {
needIndent = false
depth++
result += newline(mode, depth)
}
switch (c) {
case "{":
case "[":
needIndent = true
result += c
break
case ",":
result += c
result += newline(mode, depth)
break
case ":":
result += c
if (mode === indentMode && !inValue) {
result += " "
}
break
case "}":
case "]":
if (needIndent) {
needIndent = false
} else {
depth--
result += newline(mode, depth)
}
result += c
break
case "\"":
case "'": // if we get a `'`, replace it with `"`
inValue = !inValue
result += "\""
break
default:
result += c
}
}
return result
}
function newline(mode, depth) {
if (mode === compactMode) {
return ""
}
var line = "\n"
for (var i = 0; i < depth; i++) {
line += " "
}
return line
}我怎样才能改善这一点?
发布于 2018-04-12 13:22:31
此代码的目标不是检查文档是否具有有效的BSON语法。
但这是格式化程序的第一项要求,了解语法。任何格式化程序要工作,都必须了解输入的结构。例如,如果我在一些随机字符串中插入一个{,那么case "{":如何区分它与结构{?
因此,在某种形式上,您的解析器,无论多么简单,都需要了解其中的一些规则。您不需要构建一个健壮的解析器,您只需要知道当前字符在哪里已经遇到。
您可以使用JSON的流程图作为指南来了解何时可能遇到这样的字符。你只需要为BSON扩展它。另外,这里有一个一个简单的JS注释删除器,它不需要理解整个JS语法就可以从JS中删除注释。在gist中,它遍历字符串,根据当前状态检查当前字符(即,我是否在字符串、regexp、注释等)。然后在代码执行过程中相应地修改代码。
https://codereview.stackexchange.com/questions/191871
复制相似问题