How to add comments in Postman JSON body (for collection level pre-request script)

Viewed 836

I want to use comments within my JSON body for quick references like this:

{
    /**
    * some param info
    *   param: [
    *     1 = value so
    *     2 = value that
    *   ]
    */
    "param": [
        1
    ],
    /* some param2 info */
    "param2": "value",
    // pls use this
    "param3": [
        "values"
        //"home"
    ]
}

The comments should be filtered out before the request is getting sent to the server.

1 Answers

Finally, since Postman v8.3.0 you can do this in your collections pre-request script:

// Strip JSON Comments
if (pm?.request?.body?.options?.raw?.language === 'json') {
    const rawData = pm.request.body.toString();
    const strippedData = rawData.replace(
        /\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g,
        (m, g) => g ? "" : m
    );
    pm.request.body.update(JSON.stringify(JSON.parse(strippedData)));
}

This strips all comments from the json and sets the current body to the cleaned one, there are more examples for other body types (GraphQL, URL Encoded, Form Data) in the original github post this code is based from.

Related