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

问题描述 投票:1回答:1

我正在尝试使用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
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.