POST POST

FEB
16
2023

Allow Comments in JSON Payload in ExpressJS

ORIGINALLY POSTED TO: https://blog.simontimms.com/2023/02/16/express-json-comments

Officially comments are not supported in the JSON format. In fact this lack of ability to comment is one of the reasons that lead to the downfall of the JSON based project system during the rewrite of the .NET some years back. However they sure can be useful to support. In my case I wanted to add some comments to the body of a request to explain a parameter in Postman. I like to keep comments as close to the thing they describe as possible so I didn't want this on a wiki somewhere nobody would ever find.

The content looked something like

1
2
3
4
5
6
7
8
9
{
"data": {
"form_data": {
"effective_date": "2023-02-23",
"match_on_per_pay_period_basis": 0, /* 0 if yes, 1 if no */
"simple_or_tiered": 1, /* 0 if simple 1 if tiered */
}
}
}

This was going to an ExpressJS application which was parsing the body using body-parser. These days we can just use express.json() and avoid taking on that additional dependency. The JSON parsing in both these is too strict to allow for comments. Fortunately, we can use middleware to resolve the issue. There is a swell package called strip-json-comments which does the surprisingly difficult task of stripping comments. We can use that.

The typical json paring middleware looks like

1
2
3
4
5
app.use(express.json())

or

app.use(bodyParser.json())

Instead we can do

1
2
3
4
5
6
7
8
9
10
11
12
13
import stripJsonComments from 'strip-json-comments';

...

app.use(express.text{
type: "application/json" //
}) //or app.use(bodyParser.text({type: "application/json}))
app.use((req,res,next)=> {
if(req.body){
req.body = stripJsonComments(req.body);
}
next();
})

This still allows us to take advantage of the compression and character encoding facilities in the original parser while also intercepting and cleaning up the JSON payload.


Simon Timms

Email Email
Web Web
Twitter Twitter
GitHub GitHub
RSS

Looking for someone else?

You can find the rest of the Western Devs Crew here.

© 2015 Western Devs. All Rights Reserved. Design by Karen Chudobiak, Graphic Designer