【问题标题】:R jsonlite: create JSON data in a specific formatR jsonlite:以特定格式创建 JSON 数据
【发布时间】:2017-01-18 22:19:38
【问题描述】:

我想使用 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"
    }
  }
]

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

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

【问题讨论】:

    标签: json r jsonlite


    【解决方案1】:

    这将产生你需要的东西:

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

    【讨论】:

    • 在我的 Rstudio 中粘贴并运行您的代码会产生以下结果: > toJSON(df) [1] "{\"ID\":[100,110,200],\"Title\":[\"aa \",\"bb\",\"cc\"],\"more\":{\"有趣\":[\"yes\",\"no\",\"yes\"],\ "新\":[\"否\",\"是\",\"是\"],\"原版\":[\"是\",\"是\",\"否\"] }} 为什么?
    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 2015-09-19
    • 2022-01-21
    相关资源
    最近更新 更多