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

Fis*_*ane 0 json r jsonlite

我想使用 R 的 jsonlite 包创建 JSON 数据以使用Python加载到DynamoDB。我希望数据位于如下所示的结构中。如何在 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"
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

这是我的示例数据和我尝试过的:

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
Run Code Online (Sandbox Code Playgroud)

小智 6

这将产生你需要的东西:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

[{
        "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"
        }
    }
]
Run Code Online (Sandbox Code Playgroud)