Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a JSON with nested lists

Tags:

json

r

jsonlite

I need to dynamically construct the following 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.

like image 503
Rajesh Kumar Duraisamy Avatar asked Mar 04 '17 03:03

Rajesh Kumar Duraisamy


People also ask

Can a JSON have nested lists?

A resource representation, in the JSON format, is a complex JSON object. Lists of items and nested data structures are represented as JSON arrays and nested JSON objects.

Does JSON support nested values?

Attributes and event data can contain nested (JSON) values—arrays, objects, and arrays of objects.

What is a nested JSON file?

Nested JSON is a JSON file with a big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.

What is a list in JSON?

Similar to other programming languages, a JSON Array is a list of items surrounded in square brackets ([]). Each item in the array is separated by a comma. The array index begins with 0. The square brackets [...] are used to declare JSON array. JSON array are ordered list of values.


1 Answers

As mentioned in the comments, you can create a nested list and use 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"
  }
} 
like image 149
Rich Scriven Avatar answered Sep 21 '22 22:09

Rich Scriven