如何使用嵌套列表构造JSON

时间:2022-02-08 15:48:08

I need to dynamically construct the following JSON.

我需要动态构造以下JSON。

{
  "status": "SUCCESS",
  "code": "200",
  "output": {
    "studentid": "1001",
    "name": "Kevin"
  }
}

I tried it with the jsonlite package, but I can't construct the inner JSON object. Please help me try to resolve this.

我尝试使用jsonlite包,但我无法构造内部JSON对象。请帮我解决这个问题。

1 个解决方案

#1


8  

As mentioned in the comments, you can create a nested list and use toJSON().

如评论中所述,您可以创建嵌套列表并使用toJSON()。

library(jsonlite)
x <- list(status = "SUCCESS", code = "200", 
    output = list(studentid = "1001", name = "Kevin"))
toJSON(x, pretty = TRUE, auto_unbox = TRUE)

which gives the following output:

它给出了以下输出:

{
  "status": "SUCCESS",
  "code": "200",
  "output": {
    "studentid": "1001",
    "name": "Kevin"
  }
} 

#1


8  

As mentioned in the comments, you can create a nested list and use toJSON().

如评论中所述,您可以创建嵌套列表并使用toJSON()。

library(jsonlite)
x <- list(status = "SUCCESS", code = "200", 
    output = list(studentid = "1001", name = "Kevin"))
toJSON(x, pretty = TRUE, auto_unbox = TRUE)

which gives the following output:

它给出了以下输出:

{
  "status": "SUCCESS",
  "code": "200",
  "output": {
    "studentid": "1001",
    "name": "Kevin"
  }
}