我有一个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
}
}
]
}
答案 0 :(得分:4)
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形式将转换为R中的data.frame
对象。然后使用tibble()
放置此数据帧放入具有列名Address
的2x1数据帧中(这有点棘手,因为基本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": ""
}
}
]
}
答案 1 :(得分:2)
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": ""
}
]', simplifyDataFrame = F)
purrr::map(df, ~list(Address = .x)) %>%
list(Locations = .) %>%
jsonlite::toJSON(pretty = T, auto_unbox = T)
我认为这完全可以重现您想要的输出。