将行添加到R中生成的Json文件中

时间:2017-01-18 22:08:36

标签: json r

我想在R中生成一个JSON文件。例如:

forJson <- data.frame(names = c("John", "Mary", "Pat", "Rick"), values = 3:6)
library("jsonlite")
toJson <- toJSON(forJson, pretty = TRUE)
toJson

但是,我需要在此文件中添加一些信息。最后它应该是这样的:

[
 "CaseID": 12345,
 "graph": "Name-of-the-graph",
 "Items":[{

  {
    "names": "John",
    "values": 3
  },
  {
    "names": "Mary",
    "values": 4
  },
  {
    "names": "Pat",
    "values": 5
  },
  {
    "names": "Rick",
    "values": 6
  }]
]

我对JSON没有任何经验。感觉我表的当前值应该在一个名为&#34; Items&#34;的对象中。然后我必须在顶部有2个元信息 - CaseID和图形名称。 有关如何添加这些行或生成它们以便开始使用toJSON的任何建议吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

将您的数据放入列表中,然后将其转换为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
#       }
#       ]
# } 

略有不同的变化是在data.frame

整个list列的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 # } # ] # } # ]
fromJSON()

计算出你需要的R结构的简单方法是通过使用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 读取它来从JSON向后工作,这将自动为你提供R结构

fromJSON()

但请注意,即使CaseIDgraphtoJSON()的值作为单个元素读入,toJSON(lst, pretty = T) { "CaseID": [1234], "graph": ["name_of_graph"], "Items": [ { "names": "John", "values": 3 }, ... etc 也会自动将它们转换为数组元素(但实际上我无法看到这是一个问题。)

A