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

时间:2017-03-17 16:47:34

标签: json groovy couchdb httpbuilder

我正在尝试使用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日志的相关部分(注意未引用地图功能):

[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期间将特定值保留为纯字符串?

1 个答案:

答案 0 :(得分:0)

我最终找到了自己的问题的答案。使我困惑了大约一年的简单解决方案是将设计文档定义为String,而不是Map。对问题中的示例脚本进行以下稍作修改即可达到预期目的:

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