避免使用groovy'将某些值转换为JSON;s HTTPBuilder/RESTClient

避免使用groovy'将某些值转换为JSON;s HTTPBuilder/RESTClient,json,groovy,couchdb,httpbuilder,Json,Groovy,Couchdb,Httpbuilder,我试图使用groovy的RESTClient将设计文档添加到CouchDB数据库中。CouchDB要求设计文档中的函数(例如视图中的map/reduce函数)是字符串,而不是实际的JSONFunction对象。不幸的是,HTTPBuilder会自动将字符串解析为JSON函数,而不是将其保存为字符串。下面是一个简单的例子: import groovyx.net.http.ContentType import groovyx.net.http.RESTClient RESTClient restC

我试图使用groovy的
RESTClient
将设计文档添加到CouchDB数据库中。CouchDB要求设计文档中的函数(例如视图中的map/reduce函数)是字符串,而不是实际的JSON
Function
对象。不幸的是,
HTTPBuilder
会自动将字符串解析为JSON
函数,而不是将其保存为
字符串。下面是一个简单的例子:

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,2017年3月17日16:32:49 GMT][error][]尝试上载无效的JSON(将log_level设置为debug以记录它)
[Fri,2017年3月17日16:32:49 GMT][debug][]无效的JSON:{{错误,
{56,
词法错误:json文本中的字符串无效。\n“},
}
[2017年3月17日星期五16:32:49 GMT][info]]127.0.0.1--PUT/sampledb/_design/sample_design 400
[2017年3月17日星期五16:32:49 GMT][debug][]httpd 400错误响应:
{“error”:“bad_request”,“reason”:“invalid_json”}

我尝试在字符串中嵌入引号(即
map:“'function(doc){emit(doc.\u id,doc);}”“
;这会将值保留为字符串,但也会保留嵌入的引号,这会阻止CouchDB执行函数。有人知道我如何在转换为JSON时将特定值保留为纯字符串吗?

我最终找到了我自己问题的答案。这个简单的解决方案让我逃避了大约一年将设计文档定义为
字符串
,而不是
映射
。对问题中的示例脚本进行以下细微修改即可:

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 no longer returns 400 Bad Request at the following line and now correctly parses the
// design document!
restClient.put path: "/${databaseName}/_design/sample_design", body: document

我最终找到了我自己问题的答案。一年来,我一直没有找到一个简单的解决方案,那就是将设计文档定义为
字符串
,而不是
映射
。下面对问题中的示例脚本做了一些细微的修改:

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 no longer returns 400 Bad Request at the following line and now correctly parses the
// design document!
restClient.put path: "/${databaseName}/_design/sample_design", body: document