【发布时间】:2021-09-03 22:15:11
【问题描述】:
我有一个带有标签样式的文本列。我想将此文本拆分为列,其中列名是具有相应值的标签。
text = "{\"article_id\":-41,\"word-count\":379,\"article_date\":05012017,\"source\":\"news::abc\",\"author\":\"Peter K\",\"title\":\"The rise of AI\",\"topics\":{\"Business\":10, \"Computer\":5},\"topics-group\":[{\"primary\":\"Business\",\"secondary\":\"Computer\"}]}"
期望的输出:
data = data.frame("article_id" = -41, "word-count" = 379, "article_date" = 05012017,
"source"= "news::abc", "author" = "Peter K", "title" = "The rise of AI",
"topics" = "{\"Business\":10, \"Computer\":5}",
"topics-group" = "[{\"primary\":\"Business\",\"secondary\":\"Computer\"}]")
我试过strsplit
test = strsplit(as.character(text), ",\\\"")
test
[[1]]
[1] "{\"article_id\":-41" "word-count\":379"
[3] "article_date\":05012017" "source\":\"news::abc\""
[5] "author\":\"Peter K\"" "title\":\"The rise of AI\""
[7] "topics\":{\"Business\":10, \"Computer\":5}" "topics-group\":[{\"primary\":\"Business\""
[9] "secondary\":\"Computer\"}]}"
但是像topics-group这样的标签有问题,它被分成2个。
我的工作流程想法是完成拆分,然后对每个元素进行另一个拆分以分离标签和值。但我认为必须有更好的方法将这些标签的名称拆分和设置为列名。
【问题讨论】:
-
这是一个有点损坏的 JSON,在提供者方面修复它是有意义的。结构总是一样的吗?
-
查看使用
rjson库,但正如@Wiktor 所评论的,article_date的05012017值是八进制,JSON 不支持。将该值放在双引号中以使您的 JSON 通过验证。 -
现在我看到这是一个 JSON 类型的文件,我将进一步研究
rjson。 -
尝试
text <- gsub('("article_date":)(\\d+)', '\\1"\\2"', text),然后使用library(jsonlite)和document <- fromJSON(txt=text) -
解析 JSON 后,您可以“手动”重新格式化日期字段。