4

Why is the output of stringify missing a percent sign?

var a = ["dp",'%%'];
var t = JSON.stringify (a);
console.log ('t: ' + t);

Result is:

t: ["dp","%"]

Why isn't the result:

t: ["dp","%%"]

Thanks!

tgoneil
  • 1,522
  • 3
  • 19
  • 30

2 Answers2

6

As specified in the documentation for console.log in Node.js, the function takes arguments in a printf-like way:

The first argument is a string that contains zero or more placeholders.
Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are:

%s - String.
%d - Number (both integer and float).
%j - JSON. Replaced with the string '[Circular]' if the argument contains circular references.
%% - single percent sign ('%'). This does not consume an argument.
If the placeholder does not have a corresponding argument, the placeholder is not replaced.

Thus, any occurrence of %% in a string printed with console.log in Node.js (not browser) will be replaced by a single %. Any %s, %d or %j will be replaced by a string, number or JSON string, respectively. Here are some examples:

console.log("This is a string: %s", "Hello, World!");
//= This is a string: Hello, World!

console.log("This is a number: %d", 3.14);
//= This is a number: 3.14

console.log("This is a JSON string: %j", { value: true });
//= This is a JSON string: {"value":true}

console.log("This is a single percentage sign: %%");
//= This is a single percentage sign: %

console.log("If we use %%s and %%d here we get '%s' and '%d'.", "a string", 100);
//= If we use %s and %d here we get 'a string' and '100'.

Calling console.log in a browser, however, will just print the plain string with none of the above substitutions.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • @Frxstream do you know why would in this case: 1. if you console.log right away after setting data variable, then two of the %% are missing 2. but if you paste the variable definition in the console first and then after that paste just console.log(data), the %%%% will be there https://stackoverflow.com/questions/72286386/special-characters-string-not-properly-processing-in-js#72286386 – strix25 May 18 '22 at 09:39
  • "_in Node.js (not browser)_" - The same happens in the browser console. (At least at this point in time, for Google Chrome.) – Ivar Aug 16 '22 at 21:32
2

It doesn't have anything to do with the JSON.stringify. I can reproduce the single % output with node 0.10.36 by just doing console.log('%%'). This is likely an issue with util.format used internally for console.log by node.

https://nodejs.org/docs/latest-v0.10.x/api/util.html#util_util_format_format

However, in node 4.0 I get the expected result.

brentburg
  • 106
  • 1