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

R jsonlite: create JSON data in a specific format

我想使用 R 的 jsonlite 包创建 JSON 数据以加载到 DynamoDB using 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

这将产生您需要的东西:

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"
        }
    }
]