用双引号替换 .toString() 单引号

Replace .toString() single quotes with double quotes

也许是一个奇怪的请求,但我使用的是 CouchDB 视图,它要求字符串用双引号括起来。

这个有效:

?key=["test","234"]

这行不通:

?key=['test','234']

所以在我的 NodeJS 应用程序中,我正在尝试构建正确的密钥以传递给 CouchDB

var key1 = "test";
var key2 = "234";

{ key: [key1, key2] }

结果总是

{ key: [ 'test', '234' ] }

有什么有效的方法可以得到我想要的输出吗? (双引号)

我没有对此进行测试,但我想您可以使用 String.fromCharCode(34) 作为双引号而不是直接键入它们。所以

var key1 = String.fromCharCode(34) + 测试 + String.fromCharCode(34);

甚至

var doubleQuote = String.fromCharCode(34); var key1 = doubleQuote + test + doubleQuote;

不清楚是要传递带有键的对象还是表示对象的字符串。 如果你传递一个字符串,你为什么不使用 JSON.stringify 它使用双引号?

var key1 = "test";
var key2 = "234";
JSON.stringify({key: [key1, keys]})

这将产生: {"key": ["test", "234"]}

您可以在 node.js 应用程序中尝试此操作

var key1 = '"test"';
var key2 = '"234"';

这将导致:

{ 
   key: 
   [ 
      '"test"', 
      '"234"' 
   ] 
}

我没有用过 CouchDB,也许这会解决你的问题。

CouchDB 本身不需要 double-quotes;它需要 JSON-encoded 个参数。

这对你来说是个好消息!在 JavaScript:

中随心所欲地构建您的密钥
var key = [
    'test',
    '234'
]

然后 JSON-encode 它在发送到 CouchDB 之前:

key = JSON.stringify(key) // Result: the string '["test","234"]'