Reputation: 1968
I want to generate a JSON file in R. For example:
forJson <- data.frame(names = c("John", "Mary", "Pat", "Rick"), values = 3:6)
library("jsonlite")
toJson <- toJSON(forJson, pretty = TRUE)
toJson
However, I am required to add some info to this file. At the end it should look like this:
[
"CaseID": 12345,
"graph": "Name-of-the-graph",
"Items":[{
{
"names": "John",
"values": 3
},
{
"names": "Mary",
"values": 4
},
{
"names": "Pat",
"values": 5
},
{
"names": "Rick",
"values": 6
}]
]
I am not experienced with JSON at all. It feels like my current values for the table should be inside an object called "Items". And then I have to have 2 pieces of metainformation - CaseID and graph name - on the top. Any advice how I could add such lines or generate them to begin with using toJSON?
Thanks a lot!
Upvotes: 2
Views: 291
Reputation: 26258
Put your data in a list, and then convert it to JSON
forJson <- list(CaseID = 1234, graph = "name-of-the-graph", Items = forJson)
toJSON(forJson, pretty = T)
#
# {
# "CaseID": [1234],
# "graph": ["name-of-the-graph"],
# "Items": [
# {
# "names": "John",
# "values": 3
# },
# {
# "names": "Mary",
# "values": 4
# },
# {
# "names": "Pat",
# "values": 5
# },
# {
# "names": "Rick",
# "values": 6
# }
# ]
# }
A slight variation is to have a data.frame
inside a list
column of your overall data.frame
forJson <- data.frame(CaseID = 1234, graph = "name_of_graph")
forJson$Items <- list(data.frame(names = c("John", "Mary", "Pat", "Rick"),
values = 3:6))
toJSON(forJson, pretty = T)
# [
# {
# "CaseID": 1234,
# "graph": "name_of_graph",
# "Items": [
# {
# "names": "John",
# "values": 3
# },
# {
# "names": "Mary",
# "values": 4
# },
# {
# "names": "Pat",
# "values": 5
# },
# {
# "names": "Rick",
# "values": 6
# }
# ]
# }
# ]
The easy way to work out the R structure you need is to work backwards from the JSON by reading it in using fromJSON()
, which will automatically give you the R structure
js <- '{
"CaseID": 1234,
"graph": "name_of_graph",
"Items": [
{
"names": "John",
"values": 3
},
{
"names": "Mary",
"values": 4
},
{
"names": "Pat",
"values": 5
},
{
"names": "Rick",
"values": 6
}
]
}'
lst <- jsonlite::fromJSON(js)
lst
$CaseID
[1] 1234
$graph
[1] "name_of_graph"
$Items
names values
1 John 3
2 Mary 4
3 Pat 5
4 Rick 6
However, note that even though fromJSON()
read in the values for CaseID
and graph
as single elements, the toJSON()
automatically makes them into array elements (but in reality I can't see this being a problem).
toJSON(lst, pretty = T)
{
"CaseID": [1234],
"graph": ["name_of_graph"],
"Items": [
{
"names": "John",
"values": 3
},
... etc
Upvotes: 2