我有一个格式如下的 JSON 文件:
[
{
"StreetAddress": "",
"City": "",
"State": "",
"Zip": "V6A 2P3",
"County": "",
"Country": "",
"SPLC": "",
"CountryPostalFilter": "",
"AbbreviationFormat": "",
"CountryAbbreviation": ""
},
{
"StreetAddress": "",
"City": "",
"State": "",
"Zip": "V6A 2P3",
"County": "",
"Country": "",
"SPLC": "",
"CountryPostalFilter": "",
"AbbreviationFormat": "",
"CountryAbbreviation": ""
}
]
是否有 R 脚本可以用来重新格式化文件,如下所示:
{
"Locations": [
{
"Address": {
"StreetAddress": "1000 Herrontown Rd",
"City": "Princeton",
"State": "NJ",
"Zip": "",
"County": "",
"Country": null,
"SPLC": "",
"CountryPostalFilter": 0,
"AbbreviationFormat": 0,
"CountryAbbreviation": "US"
}
},
{
"Address": {
"StreetAddress": "457 N Harrison St",
"City": "",
"State": "",
"Zip": "08540",
"County": "",
"Country": null,
"SPLC": "",
"CountryPostalFilter": 0,
"AbbreviationFormat": 0
}
}
]
}
最佳答案
df <- jsonlite::fromJSON('[
{
"StreetAddress": "",
"City": "",
"State": "",
"Zip": "V6A 2P3",
"County": "",
"Country": "",
"SPLC": "",
"CountryPostalFilter": "",
"AbbreviationFormat": "",
"CountryAbbreviation": ""
},
{
"StreetAddress": "",
"City": "",
"State": "",
"Zip": "V6A 2P3",
"County": "",
"Country": "",
"SPLC": "",
"CountryPostalFilter": "",
"AbbreviationFormat": "",
"CountryAbbreviation": ""
}
]')
与@Brian 的回答相比,我没有设置 simplifyDataFrame = F
所以 JSON 形式将被转换为 data.frame
R 中的对象。然后使用 tibble()
将此数据框放入列名为 Address
的 2x1 数据框中(这有点棘手,因为 base data.frame()
做不到)。
res <- list(Locations = tibble::tibble(Address = df))
jsonlite::toJSON(res, pretty = T)
编辑:即使我设置了 simplifyDataFrame = F
,这个方法仍然有效,因为 tibble()
还允许命名列表作为列。
输出
{
"Locations": [
{
"Address": {
"StreetAddress": "",
"City": "",
"State": "",
"Zip": "V6A 2P3",
"County": "",
"Country": "",
"SPLC": "",
"CountryPostalFilter": "",
"AbbreviationFormat": "",
"CountryAbbreviation": ""
}
},
{
"Address": {
"StreetAddress": "",
"City": "",
"State": "",
"Zip": "V6A 2P3",
"County": "",
"Country": "",
"SPLC": "",
"CountryPostalFilter": "",
"AbbreviationFormat": "",
"CountryAbbreviation": ""
}
}
]
}
关于在 R 中重新格式化 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60193034/