【问题标题】:Issues Parsing JSON "None" with jsonlite使用 jsonlite 解析 JSON“无”的问题
【发布时间】:2022-01-09 16:41:20
【问题描述】:

我正在尝试从 UK covid 仪表板中读取有关疫苗接种数据的一些数据,这些数据将某些数据编码为 csv 文件中的 JSON。 (下载链接是here)来自疫苗接种,按页面上的疫苗接种日期年龄人口统计数据(https://coronavirus.data.gov.uk/details/vaccinations?areaType=nation&areaName=England)。提出的问题是我的代码不再成功地将 JSON 数据扩展为 data.frame。当数据遇到 None 对象时,这似乎是一个解析问题。

我的代码读取数据如下(此代码在 2021-11-25 下载的数据上成功,但在 2021-12-02 数据上失败)。下面的代码在 fromJSON 命令上失败,该命令现在在到达“Arg”时出错:None 声称存在词法错误。错误信息显示在代码下方。

library(tidyverse)
library(jsonlite)

#! Read in the latest national dashboard data
df <- read_csv("<filepath>")

df |> 
  mutate(vaccinationsAgeDemographics = map(vaccinationsAgeDemographics, ~fromJSON(. |> str_replace_all("'", "\"")))) |> 
  unnest(cols = c(vaccinationsAgeDemographics))
Error: Problem with `mutate()` column `vaccinationsAgeDemographics`.
i `vaccinationsAgeDemographics = map(...)`.
x lexical error: invalid char in json text.
          yVaccinationDatePercentage": None}, {"age": "16_17", "Vaccin
                     (right here) ------^

简化的测试线如下:

fromJSON(df$vaccinationsAgeDemographics[1] |> str_replace_all("'", "\""))

引发类似错误:

Error: lexical error: invalid char in json text.
          yVaccinationDatePercentage": None}, {"age": "16_17", "Vaccin
                     (right here) ------^

【问题讨论】:

  • 作为快速修复,我刚刚将字符串中的这些值替换为 jsonlite 可以处理的值,但现在这似乎不是最理想的

标签: r json tidyverse jsonlite


【解决方案1】:

我已经设法解决了这个问题,因为可能的 json 映射在此处的 jsonlite 文档中进行了讨论:https://cran.r-project.org/web/packages/jsonlite/vignettes/json-mapping.pdf

预先知道数据是数字类型,并且 None 不包含在任何指标名称中,我们可以使用以下代码将 None 字符串替换为 "NA"

library(tidyverse)
library(jsonlite)

df <- read_csv("C:\\Users\\joel.kandiah\\Downloads\\data_2021-Dec-02.csv")

fromJSON(df$vaccinationsAgeDemographics[1] |> str_replace_all("'", "\"") |> str_replace_all("None", "\"NA\""))

【讨论】:

    猜你喜欢
    • 2016-05-18
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2018-12-20
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多