R jsonlite:以特定格式创建JSON数据

时间:2017-01-18 13:48:21

标签: json r jsonlite

我想使用R的jsonlite包创建JSON数据,以使用DynamoDB加载到Python。我希望数据在下面显示的结构中。我怎样才能在R中创建它?我尝试创建一个数据框,其中一列是列表,并将数据框更改为json,但结果不是所需的格式。我也尝试过转换包含列表的列表,但输出json的结构不是我想要的。

[
{
    "ID": 100,
    "title": "aa",
    "more": {
      "interesting":"yes",
      "new":"no",
      "original":"yes"
    }
},

{
    "ID": 110,
    "title": "bb",
    "more": {
      "interesting":"no",
      "new":"yes",
      "original":"yes"
    }
},

{
    "ID": 200,
    "title": "cc",
    "more": {
      "interesting":"yes",
      "new":"yes",
      "original":"no"
    }
  }
]

以下是我的示例数据以及我尝试的内容:

library(jsonlite)

ID=c(100,110,200)
Title=c("aa","bb","cc")
more=I(list(Interesting=c("yes","no","yes"),new=c("no","yes","yes"),original=c("yes","yes","no")))

 a=list(ID=ID,Title=Title,more=more)
 a=toJSON(a)
 write(a,"temp.json")  # this does not give the structure I want

1 个答案:

答案 0 :(得分:4)

这将产生你需要的东西:

library(jsonlite)

ID=c(100,110,200)
Title=c("aa","bb","cc")

df <- data.frame(ID, Title)
more=data.frame(Interesting=c("yes","no","yes"),new=c("no","yes","yes"),original=c("yes","yes","no"))
df$more <- more

toJSON(df)

输出:

[{
        "ID": 100,
        "Title": "aa",
        "more": {
            "Interesting": "yes",
            "new": "no",
            "original": "yes"
        }
    }, {
        "ID": 110,
        "Title": "bb",
        "more": {
            "Interesting": "no",
            "new": "yes",
            "original": "yes"
        }
    }, {
        "ID": 200,
        "Title": "cc",
        "more": {
            "Interesting": "yes",
            "new": "yes",
            "original": "no"
        }
    }
]