我是R的初学者(仍然在Coursera上学习"R编程"课程),我正在尝试练习R将一些简单的代码从Python移植到R。
目前,我正在尝试对KairosDB数据库进行API调用。为了进行查询,我需要使用 json.dumps()
(来自json
本机库)对 Python 对象进行编码,但我已经搜索了很多,我不明白如何使用 R 做到这一点,它是jsonlite
库。我什至不知道我是否正在正确创建 JSON 对象,但这就是我在某些搜索中找到的。
我用Python 3编写的代码(来自这个存储库):
import requests
import json
kairosdb_server = "http://localhost:8080"
# Simple test
query = {
"start_relative": {
"value": "4",
"unit": "years"
},
"metrics": [
{
"name": "test",
"limit": 10000
}
]
}
response = requests.post(kairosdb_server + "/api/v1/datapoints/query", data=json.dumps(query))
print("Status code: %d" % response.status_code)
print("JSON response:")
print(response.json())
我目前用 R 3.2.3 编写的代码:
library(httr)
library(jsonlite)
kairosdb_server <- 'http://localhost:8080'
query <- serializeJSON(toJSON('
"start_relative": {
"value": "4",
"unit": "years"
},
"metrics": [
{
"name": "test",
"limit": 1000
}
]
'))
url <- paste(kairosdb_server, '/api/v1/datapoints/query')
response <- POST(url, body = query, encode = 'json')
print(paste("Query status code: ", response$status_code))
print(paste("JSON response: n", content(response, type = 'application/json')))
如果我运行它,我得到以下错误:
print(paste("Query status code: ", response$status_code))
# [1] "Query status code: 400"
print(paste("JSON response: n", content(response, type = 'application/json')))
# [1] "JSON response: n list("query.metric[] must have a size of at least 1")"
我做错了什么?
通常人们会将命名list
传递到body
但是试图让 R 在"指标"中保留数组是很棘手的。既然你已经有了原始Python结构的JSON,为什么不直接添加括号并将其作为字符向量传递呢?即
query <- '{"start_relative": {
"value": "4",
"unit": "years"
},
"metrics": [
{
"name": "test",
"limit": 10000
}
]}'
(然后只需在POST
中使用该query
)。它相当于json.dumps()
吐出的JSON:
# get rid of newlines and spaces just to show they are the same,
# the server won't (shouldn't) care if there are newlines/spaces
cat(gsub(" \]", "]", gsub("\[ ", "[", gsub(" \}", "}", gsub("\{ ", "{", gsub(" +", " ", gsub("\n", "", query)))))))
{"start_relative": {"value": "4", "unit": "years"}, "metrics": [{"name": "test", "limit": 10000}]}
# python
json.dumps(query)
'{"metrics": [{"limit": 10000, "name": "test"}], "start_relative": {"unit": "years", "value": "4"}}'
如果确实需要使用 R 数据结构,则最终将操作 toJSON
的输出。