简体   繁体   中英

Equivalent of Python “json.dumps()” in R?

I'm a very beginner student of R (still coursing the "R Programming" course on Coursera) and I'm trying to practice R porting some easy code from Python to R.

Currently I'm trying to make API calls for a KairosDB database . In order to make the query, I need to encode the Python object with json.dumps() (from the json native library), but I've searched a lot and I don't get how I can do that with R and it's jsonlite library. I don't even know if I'm creating the JSON object corretly, but that's what I've found in some searches.

My code written in 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())

My current code written in 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')))

If I run that I got the following error:

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\")"

What I'm doing wrong?

Normally one would pass a named list into body but trying to get R to preserve the array in "metrics" is tricky. Since you kinda already have JSON with the original Python structure, why not just add brackets and pass it in as a character vector? ie

query <- '{"start_relative": {
    "value": "4",
    "unit": "years"
  },
  "metrics": [
    {
      "name": "test",
      "limit": 10000
    }
  ]}'

(then just use that query in the POST ). It's equivalent JSON to what json.dumps() spits out:

# 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"}}'

If you do need an R data structure to work with, you're going to end up manipulating the output of toJSON .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM