Codebricks
Codebricks

Reputation: 1263

Remove trailing spaces in json string c#

I have a large json string that I need to remove any number of leading and trailing spaces from property values (in c#) e.g.

"Some Property Name": " Some Value "

needs to change to:-

"Some Property Name": "Some Value"

I have the option to do this via a regex replace on the json string before it is converted into a newtonsoft json object, or loop through the json object's properties after it has been converted.

Anybody any thoughts on the best way to do this?

Upvotes: 1

Views: 2380

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

Your second option is the safest one.

Any time that you have to modify a structured text of some kind (XML, HTML, JSON, C#, etc.) the safest option is to parse, modify, and re-format. Otherwise, you run the risk of changing things that you did not plan to change.

In your particular scenario a regex solution may unintentionally strip leading spaces from quoted strings inside a string, for example

"Some Property Name": " Say \"   Hello, world!\" two times "

Corner cases like this often go unnoticed when developing a regex-based solution. On the other hand, parser-based solutions do not treat these situations as "corner cases," because all the complexity of understanding the format is shifted into the parser.

Upvotes: 3

Related Questions