这是我在R中加载的日志模板的结构,我如何清理它以生成数据帧?
{"ask":{"Id":001,"TS":10012001,"Response":"12"}}
{"ask":{"Id":002,"TS":11012001,"Response":"10"}}预期的输出应该是单独的列,它们的值在数据框中,以便进一步分析。
发布于 2017-02-03 10:35:53
由于这些行几乎都是有效的JSON,除了应该用引号括起来的前导零编号字符串之外,请考虑清除有效的JSON,并使用jsonlite作为单行数据帧导入。然后行绑定列表中所有单独的df元素。下面迭代地读取log中的行,以转换每一行:
library(jsonlite)
loglines <- readLines("/path/to/log.txt")
dfList <- lapply(loglines, function(line){
# JSON CONVERT WITH QUOTE AND BRACKET WRAPPING
jsonline <- paste0("[", gsub(',"TS', '","TS', gsub('Id":', 'Id":"', line)), "]")
fromJSON(jsonline)[[1]]
})
df <- do.call(rbind, dfList)
rownames(df) <- NULL发布于 2017-02-03 11:07:43
library(V8)
library(jqr)
library(tidyverse)
txt <- '{"ask":{"Id":001,"TS":10012001,"Response":"12"}}
{"ask":{"Id":002,"TS":11012001,"Response":"10"}}'
lines <- readLines(textConnection(txt))V8帮助器
ctx <- v8()
map_df(lines, function(x) {
ctx$eval(sprintf("var dat=%s", JS(x)))
ctx$get("dat") %>%
unlist() %>%
as.list()
})
## # A tibble: 2 × 3
## ask.Id ask.TS ask.Response
## <chr> <chr> <chr>
## 1 1 10012001 12
## 2 2 11012001 10jqr + jsonlite帮助器
map(lines, jq, ".") %>%
map(jsonlite::fromJSON) %>%
map(unlist) %>%
map_df(as.list)
## # A tibble: 2 × 3
## ask.Id ask.TS ask.Response
## <chr> <chr> <chr>
## 1 1 10012001 12
## 2 2 11012001 10jqr + ndjson帮助器
map(lines, jq, ".") %>%
map(flags, pretty=FALSE) %>%
map_df(~ndjson::flatten(.$data))
## Source: local data table [2 x 3]
##
## # tbl_dt [2 × 3]
## ask.Id ask.Response ask.TS
## <dbl> <chr> <dbl>
## 1 1 12 10012001
## 2 2 10 11012001如果有必要,mutate() + sprintf()你的领导0的背部
发布于 2017-02-03 07:51:16
这里有一个快速的解决方案:
1.将整个文件作为字符数组读取:
sfile <- readLines(file)2.使用gsub清理sfile,假设结构与原始示例完全相同:
sfile <- gsub("{ \"ask\": { \"Id\":| \"TS\":| \"Response\":\"|\" }}", "", sfile, perl = TRUE)3.现在将其读取为逗号分隔值(read.csv接受字符串而不是文件作为输入)
df <- read.csv(file=sfile)4.命名列
names(df) <- c("Id", "TS", "Response")下面是一个使用数组而不是输入文件的测试:
s <- c( '{ "ask": { "Id":001, "TS":10012001, "Response":"12" }}',
'{ "ask": { "Id":002, "TS":11012001, "Response":"10" }}'
)现在,您将获得一个逗号分隔的字符数组
> gsub("{ \"ask\": { \"Id\":| \"TS\":| \"Response\":\"|\" }}", "", s, perl = TRUE)
[1] "001,10012001,12" "002,11012001,10"https://stackoverflow.com/questions/42013512
复制相似问题