2

大家好!我有用于解析 JSON 文件的简单 R 脚本:

json <- 
   rjson::fromJSON(readLines('http://data.rada.gov.ua/ogd/zpr/skl8/bills-
   skl8.json', warn=F))
bills <-  data.frame(
  id = numeric(), 
  title = character(),
  type = character(), 
  subject = character(), 
  rubric = character(),
  executive = character(),
  sesion = character(),
  result = character() 
)
for (row in json) 
{
  bill <- data.frame(
    id = row$id, 
    title = row$title, 
    type = row$type,
    subject = row$subject, 
    rubric = row$rubric,
    executive = row$mainExecutives$executive$department,
    sesion = row$registrationSession,
    result = row$currentPhase$title
)
  bills <- rbind(bills, bill)
}

但是我在 data.frame(id = row$id, title = row$title, type = row$type, subject = row$subject, 中有错误:参数暗示不同的行数:1, 0

所以,我的 JSON 文件在 277 行有 NULL 值。我可以跳过此错误或替换循环中的 NULL 值吗?谢谢!

4

2 回答 2

1

为此目的fromJSONjsonlite包)可能很方便。

library(jsonlite)

url <- 'http://data.rada.gov.ua/ogd/zpr/skl8/bills-skl8.json'
df <- jsonlite::fromJSON(url)   

df1 <- data.frame(
  id = df$id, 
  title = df$title, 
  type = df$type,
  subject = df$subject, 
  rubric = df$rubric,
  executive = df$mainExecutives$executive$department,
  sesion = df$registrationSession,
  result = df$currentPhase$title
)
于 2018-03-12T18:26:50.387 回答
1

为了回答您的直接问题,我将使用一个小函数包装它,如果缺少执行部门,该函数将返回一个字符串。

protect_against_null <- function( x ) {
  if( is.null(x) )
    return( "" ) # Replace with whatever string you'd like.
  else 
    return( x )
}

for (row in json) {
  bill <- data.frame(
    id = row$id, 
    title = row$title, 
    type = row$type,
    subject = row$subject, 
    rubric = row$rubric,
    executive = protect_against_null(row$mainExecutives$executive$department),
    sesion = row$registrationSession,
    result = row$currentPhase$title
  )
  bills <- rbind(bills, bill)
}

长期建议:由于该数据集包含 11,000 条嵌套记录,因此我会避开循环。查看purrr包,将嵌套的 json/list 映射到矩形数据框。特别是purrr::map_dfr()

于 2018-03-12T17:03:12.380 回答