You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R与rjson库获取JSON对象并实现Plumber R HTTP包响应?

Hey there! Let's walk through exactly how to work with Plumber's HTTP response features and handle JSON objects using R's rjson library. I'll share practical, runnable examples so you can implement this right away.

1. Mastering Plumber's HTTP Response Functions

Plumber is built to make crafting custom HTTP responses intuitive. Here are the core use cases you'll need:

Basic JSON Responses

By default, Plumber automatically converts R objects (lists, data frames, etc.) to JSON. But if you want full control over status codes or headers, use the response() function:

# Save this as plumber.R
#* @get /api/greet
function() {
  # Create your data as an R list
  response_data <- list(
    status = "success",
    message = "Hello from your Plumber API!",
    user_details = list(user_id = 456, subscription = "premium")
  )
  
  # Return a structured JSON response
  plumber::response(
    status = 200,  # Standard success code
    body = response_data,
    contentType = "application/json"
  )
}

To run this, just execute plumber::plumb("plumber.R")$run(port = 8000) and visit http://localhost:8000/api/greet in your browser.

Custom Status Codes & Headers

Need to return error codes (like 400 for bad requests) or add custom headers? Here's how to do it:

#* @get /api/user
function(req, res) {
  # Check if the required 'user_id' query parameter is present
  if (is.null(req$query$user_id)) {
    res$status <- 400  # Bad request code
    return(list(error = "Missing required parameter: user_id"))
  }
  
  # Add a custom header to the response
  res$setHeader("X-API-Version", "1.0.0")
  
  # Return success data
  list(
    status = "success",
    user_id = req$query$user_id,
    message = "User data retrieved successfully"
  )
}

Returning Non-JSON Content

Plumber isn't limited to JSON—you can return plain text, HTML, or even files. For example, a plain text response:

#* @get /api/text
function() {
  plumber::response(
    body = "This is a plain text response, not JSON!",
    contentType = "text/plain"
  )
}

2. Working with JSON in R Using rjson

The rjson package is a lightweight, easy-to-use tool for parsing and generating JSON. Let's cover the essentials:

Install & Load the Package

First, get the package set up:

install.packages("rjson")  # Run once
library(rjson)

Parse JSON Strings to R Objects

If you have a JSON string (from an API request, file, or elsewhere), convert it to an R list with fromJSON():

# Sample JSON string
json_input <- '{"product": "Laptop", "price": 999.99, "in_stock": true, "tags": ["electronics", "portable"]}'

# Convert to R object
r_object <- fromJSON(json_input)

# Access elements like any R list
print(r_object$product)  # Output: "Laptop"
print(r_object$tags[2])  # Output: "portable"

Convert R Objects to JSON Strings

Use toJSON() to turn R objects into valid JSON. This is handy if you need to manually craft JSON (though Plumber does this automatically for responses):

# Create an R data frame
inventory <- data.frame(
  item_id = c(101, 102, 103),
  name = c("Mouse", "Keyboard", "Monitor"),
  stock = c(50, 25, 10)
)

# Convert to JSON string
json_output <- toJSON(inventory)
cat(json_output)

Read JSON from Files

If you have a JSON file stored locally, read it directly with fromJSON():

# Read JSON data from a file
json_data <- fromJSON(file = "inventory.json")

Putting it all together, you can use rjson to parse incoming JSON requests in Plumber (access raw request body with req$postBody) or generate JSON for custom responses. Plumber handles most serialization automatically, but knowing rjson gives you extra flexibility for edge cases.

内容的提问来源于stack exchange,提问作者Edgaras Karka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:05:36