【问题标题】:Avoid converting some values to JSON with groovy's HTTPBuilder/RESTClient避免使用 groovy 的 HTTPBuilder/RESTClient 将某些值转换为 JSON
【发布时间】: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


    【解决方案1】:

    我最终找到了自己问题的答案。困扰我大约一年的简单解决方案是将设计文档定义为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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2016-01-11
      • 2017-07-06
      • 2023-03-09
      • 2013-03-06
      • 2014-07-27
      • 1970-01-01
      相关资源
      最近更新 更多