Click here to Skip to main content
15,847,427 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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


I have tried but it removes all spaces inside or like
"label":"First Name"
converts into

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); 
Updated 15-Feb-18 2:25am
Afzaal Ahmad Zeeshan 15-Feb-18 7:21am    
Are you building this JSON serializer? Because if someone else is serializing this, then they should take care of this part.

If you are doing this, then remove any spaces while parsing.
itsathere 15-Feb-18 7:29am    
No, I am not building it. I am getting json format and inserting it to database and again trying to use that json and getting exception.
F-ES Sitecore 15-Feb-18 7:26am    
You say you want to remove spaces and also you want it on one line, so are you wanting to remove the spaces or the line breaks?

Regardless this is one of those questions where it looks like you're trying to solve the wrong problem. If you are deserialising your json properly it shouldn't matter that the spaces or line breaks are there.
itsathere 15-Feb-18 7:31am    
I want to remove space and line breaks too. As I have mentioned the format above.
F-ES Sitecore 15-Feb-18 7:41am    

s = s.Replace("\r\n", "")

to get rid of line breaks, see Solution 1 for the spaces

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");

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#[^]
Share this answer
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[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900