【发布时间】:2017-03-17 16:47:34
【问题描述】:
我正在尝试使用 groovy 的 RESTClient 将设计文档添加到 CouchDB 数据库。 CouchDB 要求设计文档中的函数(例如视图中的 map/reduce 函数)是字符串,而不是实际的 JSON Function 对象。不幸的是,HTTPBuilder 自动将字符串解析为 JSON Function,而不是将其保存为 String。这是一个简单的例子:
import groovyx.net.http.ContentType
import groovyx.net.http.RESTClient
RESTClient restClient = new RESTClient('http://localhost:5984', ContentType.JSON)
def databaseName = 'sampledb'
restClient.put path: "/${databaseName}" // Create the sample DB
def document = [
language: 'javascript',
views: [
sample_view: [
map: 'function(doc) { emit(doc._id, doc); }'
]
]
]
// CouchDB returns 400 Bad Request at the following line
restClient.put path: "/${databaseName}/_design/sample_design", body: document
这里是CouchDB日志的相关部分(注意map函数没有被引用):
[Fri, 17 Mar 2017 16:32:49 GMT] [error] [<0.18637.0>] attempted upload of invalid JSON (set log_level to debug to log it)
[Fri, 17 Mar 2017 16:32:49 GMT] [debug] [<0.18637.0>] Invalid JSON: {{error,
{56,
"lexical error: invalid string in json text.\n"}},
<<"{\"language\":\"javascript\",\"views\":{\"sample_view\":{\"map\":function(doc) { emit(doc._id, doc); }}}}">>}
[Fri, 17 Mar 2017 16:32:49 GMT] [info] [<0.18637.0>] 127.0.0.1 - - PUT /sampledb/_design/sample_design 400
[Fri, 17 Mar 2017 16:32:49 GMT] [debug] [<0.18637.0>] httpd 400 error response:
{"error":"bad_request","reason":"invalid_json"}
我尝试在字符串中嵌入引号(即map: '"function(doc) { emit(doc._id, doc); }"';这会将值保留为字符串,但它也保留嵌入的引号,这会阻止 CouchDB 执行该函数。有谁知道我如何保留特定的在转换为 JSON 期间将值作为纯字符串?
【问题讨论】:
标签: json groovy couchdb httpbuilder