Complete the code to convert a list to JSON using jsonlite.
library(jsonlite) my_list <- list(name = "Alice", age = 25) json_data <- toJSON([1]) print(json_data)
The toJSON() function converts an R object like my_list into JSON format.
Complete the code to prettify JSON output with jsonlite.
library(jsonlite) my_list <- list(city = "Paris", population = 2148327) json_data <- toJSON(my_list, [1] = TRUE) cat(json_data)
auto_unbox which controls single values, not formatting.digits with formatting.The pretty = TRUE option formats JSON with indentation and line breaks for readability.
Fix the error in the code to parse JSON string back to R object.
library(jsonlite) json_str <- '{"fruit":"apple","count":10}' my_data <- [1](json_str) print(my_data)
toJSON() which converts R to JSON, not the other way.parseJSON().The fromJSON() function converts a JSON string back into an R object.
Fill both blanks to create a JSON from a named vector and parse it back.
library(jsonlite) vec <- c(a = 1, b = 2, c = 3) json_vec <- [1](vec, [2] = TRUE) parsed_vec <- fromJSON(json_vec) print(parsed_vec)
fromJSON in the first blank which is for parsing JSON.auto_unbox instead of pretty for formatting.Use toJSON() to convert the vector, and pretty = TRUE to format the JSON nicely.
Fill all three blanks to convert a data frame to JSON with unboxed values and parse it back.
library(jsonlite) df <- data.frame(name = c("Tom", "Sue"), age = c(30, 25)) json_df <- [1](df, [2] = TRUE) parsed_df <- [3](json_df) print(parsed_df)
pretty instead of auto_unbox for the second blank.toJSON instead of fromJSON for parsing.Use toJSON() to convert the data frame, auto_unbox = TRUE to avoid arrays for single values, and fromJSON() to parse back.