缩小缩进JSON字符串在.NET [英] Minify indented JSON string in .NET
问题描述
我有锯齿状的JSON字符串例如。
{
一:1
}
不过,我并没有实例被序列化或反序列化的类型。的
在我的情况,有什么最有效的方法为缩小 JSON字符串?例如,
{一:1}
我不介意使用图书馆,如果他们的生产做好了准备。
谢谢, 马克斯
Regex.Replace(myJSON,(\(?:[^ \\\\\] | \ \\\)* \。)| \\ S +,$ 1)
应该这样做。它确保了包含空格字符的字符串是preserved,和所有其他的空格字符将被丢弃。所有的JSON关键字(假
,真
,空
)有必须由逗号或其他标点符号所以只有空白字符串中分离出来需要是preserved。
第一个选项(\(:[^ \?\\\\] | \\\\)* \。)
匹配一个双引号的字符串该(...)
意味着输出被捕获并在替换为 $ 1
提供的 [^ \\\\\]
除了双引号的任何字符匹配或转义符 \
。
由于匹配时左到右,第二个选项, \ S +
不会在字符串中匹配的空间。
所以我们整个匹配的字符串,和空格之外的字符串。在前一种情况下, $ 1
是字符串标记,而在后一种情况下, $ 1
是因为第1组空字符串不使用
这按预期工作,因为
- 在JSON唯一的令牌,可以包含空格的双引号字符串。有没有单引号的字符串或注释的JSON。
- JSON的语法要求所有多字符标记之间的单字符标点,因此删除空间不会合并标记。在JavaScript中,这可能是有问题的,因为空间是需要打破的令牌;
变种X = 0
是VARx前提= 0
和X个不同 - - (Y)
是X个不同 - (Y)
I have an indented JSON string e.g.
{
"a": 1
}
However, I don't have the type of the instance to be serialized or deserialized.
In my situation, what's the most efficient way to minify a JSON string? e.g.
{"a":1}
I don't mind using libraries if they are production-ready.
Thanks, Max
Regex.Replace(myJSON, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1")
should do it. It makes sure that strings that contain space characters are preserved, and all other space characters are discarded. All JSON keywords (false
, true
, null
) have to be separated by commas or other punctuation so only white-space inside strings needs to be preserved.
The first option (\"(?:[^\"\\\\]|\\\\.)*\")
matches a double quoted string. The (...)
mean that the output is captured and available in the replacement as $1
. The [^\"\\\\]
matches any character except a double quote or escape character \
.
Since matching occurs left-to-right, the second option, \s+
will not match space inside a string.
So we match whole strings, and spaces outside strings. In the former case, $1
is the string token, and in the latter case $1
is the empty string because group 1 was not used.
This works as intended because
- the only tokens in JSON that can contain spaces are double-quoted strings. There are no single-quoted strings or comments in JSON.
- the JSON grammar requires single-character punctuation between all multi-character tokens, so removing space will not merge tokens. In JavaScript, this could be problematic because space is required to break tokens;
var x=0
is different fromvarx=0
andx - -(y)
is different fromx--(y)
.
这篇关于缩小缩进JSON字符串在.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!