I am putting some results together in a nested list (with arrays). The expected results must be EXACTLY as follows:
{
"item1": "TEXT",
"item2": "MORE TEXT",
"item3": [
"STILL TEXT"
],
"item4": [
"TEXT AGAIN"
],
"values": [
{
"start": 0,
"end": 99
}
]
}
I put all my results together like this:
listToJson <- c(list(item1 = "TEXT",
item2 = "MORE TEXT",
item3 = "STILL TEXT",
item4 = "TEXT AGAIN",
values = list(start = 99,
end = 0)))
write_json(listToJson, path = "test.json", auto_unbox = TRUE , null = "null")
The problem is that the results doesn't have array elements (see below). item3
and item4
should be arrays. How can I change my code to get the expected results in that exact format?
{
"item1":"TEXT",
"item2":"MORE TEXT",
"item3":"STILL TEXT",
"item4":"TEXT AGAIN",
"values":{
"start":99,
"end":0}
}
CodePudding user response:
You can just use as.array
for those specific items.
library(jsonlite)
listToJson <- c(
list(
item1 = "TEXT",
item2 = "MORE TEXT",
item3 = as.array("STILL TEXT"),
item4 = as.array("TEXT AGAIN"),
values = as.array(list(start = 99,
end = 0))
)
)
write_json(listToJson, path = "test.json", auto_unbox = TRUE , null = "null")
Output
{
"item1":"TEXT",
"item2":"MORE TEXT",
"item3":[
"STILL TEXT"
],
"item4":[
"TEXT AGAIN"
],
"values":[
{
"start":0,
"end":99
}
]
}