删除json字符串中的额外空格 [英] Remove extra space in json string
问题描述
我试图从json格式的字符串中删除所有空格,因此我需要单行字符串中的所有json。
如下所示
I am trying to remove all spaces from json formatted string and as a result i need all json in single line string.
Like below
[{"type":"text","label":"FirstName","name":"firstname","subtype":"text","className":"redform-control"},{"type":"select","label":"Profession","className":"form-control","name":"profession","values":[{"label":"StreetSweeper","value":"StreetSweeper"},{"label":"BrainSurgeon","value":"BrainSurgeon"}]},{"type":"textarea","label":"ShortBio:","className":"form-control","name":"short-bio","subtype":"textarea","rows":"4"}]
我试过了但它删除了里面的所有空格或者像
I have tried but it removes all spaces inside or like
"label":"First Name"
转换为
converts into
"label":"FirstName"
我需要一个单行字符串,但内部反转的逗号数据不会受到影响。
我尝试过:
I need it in a single line string but inside inverted comma data would not be affected.
What I have tried:
var content = Regex.Replace(jsonContent, @"\s+", string.Empty);
推荐答案
此主题 c# - csharp删除空格,除非在引号内,忽略转义引号 [ ^ ]建议使用JSON解析器为您执行此操作或Wiktor建议这个正则表达式代替
This thread c# - csharp remove white spaces unless within quotes, ignoring escaped quotes[^] suggests using a JSON parser to do this for you or Wiktor suggests this regex instead
var content = Regex.Replace(jsonContent, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "
1);
1");
这里有关于CP重新解析JSON的文章可能有帮助
使用C#在JSON中从零到英雄 [ ^ ]
< a href =https://www.codeproject.com/Articles/349646/Dynamic-JSON-parser>动态JSON解析器 [ ^ ]
和可能用C#反序列化JSON [ ^ ]
There is are articles here on CP re parsing JSON that might help
From zero to hero in JSON with C#[^]
Dynamic JSON parser[^]
and possibly Deserialize JSON with C#[^]
通常情况下,我会让JSON序列化程序执行此操作,但您如何告诉它执行此操作取决于您使用的序列化程序。
但您可以使用正则表达式缩小JSON数据:敏ify在.NET中缩进JSON字符串 - Stack Overflow [ ^ ]
Normally, I'd let the JSON serializer do that, but how you tell it to do that will depend on the serializer you use.
But you can minify JSON data with a regex: Minify indented JSON string in .NET - Stack Overflow[^]
这篇关于删除json字符串中的额外空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!