The dangerous side of JSON.stringify

Arun Rajeevan
2 min readOct 25, 2018

--

Recently i came across one issue.

I have a client that generates a signature based on the json string of request body and send it with request. The server verifies the signature.
The problem was : The client was using postman tool to create signature.
In postman,you have a visual editor to create your JSON request payload.

Let’s take an example:
Consider the req body is:{“name”:”mjuuh”,”description”:”new service”}

If you create the JSON req body in single line in postman,you will get the request body in json string format as “{\”name\”:\”kddjdososos\”,\”description\”:\”new service\”}”

Now if you use multi lines,like shown below

The json string generated by postman will be : “{\”name\”:\”kddjdososos\”,\n\”description\”:\”new service\”}”

Have you seen the ‘\n’?
Yes,it is a valid json.

But if i do,
var a=JSON.parse(“{\”name\”:\”kddjdososos\”,\”description\”:\”new service\”}”);

var b=JSON.parse(“{\”name\”:\”kddjdososos\”,\n\”description\”:\”new service\”}”);

a and b will be same.

Note: But the signature for the same JSON object were different because their JSON string representation were different.

Definition of JSON.stringify
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Syntax

JSON.stringify(value[, replacer[, space]])

Parameters
1) value
The value to convert to a JSON string.

2) replacer (Optional)
A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.

3) space (Optional)
A String or Number object that’s used to insert white space into the output JSON string for readability purposes.
If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used.

If this is a String, the string (or the first 10 characters of the string, if it’s longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.

Examples:
JSON.stringify({}); // '{}'

JSON.stringify(true); // 'true'

JSON.stringify('foo'); // '"foo"'

JSON.stringify([1, 'false', false]); // '[1,"false",false]'

JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'

--

--

No responses yet