我是R的初学者(仍然在编程" R编程" Coursera课程),我试图练习将一些简单的代码从Python移植到R. / p>
目前,我正在尝试为KairosDB database进行API调用。为了进行查询,我需要使用json.dumps()
(来自json
本机库)对Python对象进行编码,但我已经搜索了很多内容并且我不知道如何我可以用R和它的jsonlite
库来做到这一点。我甚至不知道我是否正确地创建了JSON对象,但这是我在某些搜索中发现的。
我的代码用Python 3编写(from this repo):
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\")"
我做错了什么?
答案 0 :(得分:2)
通常会将名为list
的{{1}}传递给body
,但是尝试让R在“指标”中保留数组是很棘手的。既然你已经拥有了原始Python结构的JSON,为什么不只是添加括号并将其作为字符向量传递?即
query <- '{"start_relative": {
"value": "4",
"unit": "years"
},
"metrics": [
{
"name": "test",
"limit": 10000
}
]}'
(然后只使用query
中的POST
。它等同于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
的输出。