【问题标题】:Javascript stringify '%%' loses a percent signJavascript stringify '%%' 丢失百分号
【发布时间】:2016-01-15 18:23:24
【问题描述】:

为什么 stringify 的输出缺少百分号?

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

结果是:

t: ["dp","%"]

为什么不是结果:

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

谢谢!

【问题讨论】:

  • 我无法重现这一点,我运行了您发布的确切代码并得到了后者的结果。
  • 我用 node.js v0.10.36 运行它
  • 有趣。我刚刚用 JSBin 运行,也得到了后者的结果。

标签: javascript json stringify


【解决方案1】:

如 Node.js 中 console.log 的文档中所述,该函数接受 printf-like way 中的参数:

第一个参数是一个包含零个或多个占位符的字符串。
每个占位符都被其对应参数的转换值替换。支持的占位符有:

%s - 字符串。
%d - 数字(整数和浮点数)。
%j - JSON。如果参数包含循环引用,则替换为字符串“[Circular]”。
%% - 单个百分号 ('%')。这不会消耗参数。
如果占位符没有对应的参数,则不替换占位符。

因此,在使用console.log 在 Node.js 中(不是浏览器)打印的字符串中任何出现的%% 都将被单个% 替换。任何%s%d%j 都将分别替换为字符串、数字或JSON 字符串。以下是一些示例:

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'.

但是,在浏览器中调用 console.log 只会打印没有上述替换的纯字符串。

【讨论】:

    【解决方案2】:

    它与JSON.stringify 没有任何关系。我只需执行console.log('%%') 就可以用node 0.10.36 重现单个% 输出。这可能是节点内部用于console.logutil.format 的问题。

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

    但是,在node 4.0 中,我得到了预期的结果。

    【讨论】:

    • 感谢您的提示。刚刚升级到节点 4.2.1,现在还可以根据需要获得 %%。
    猜你喜欢
    • 2016-01-27
    • 2013-10-03
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2011-02-19
    相关资源
    最近更新 更多