You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中将无固定结构JSON字符串列拆分为多列并补全空值

解决方法

核心问题是你存储的类JSON字符串使用单引号包裹键和值,不符合标准JSON的双引号规范,先做引号替换再用JSON解析工具即可快速拆分字段,10万行数据量级下也能高效处理。

第一步:安装依赖包(未安装过的情况下运行)

install.packages(c("tidyverse", "jsonlite"))

第二步:运行处理代码

# 加载工具包
library(tidyverse)
library(jsonlite)

# 这里替换为你自己导入的Excel数据框,示例用你提供的input
input <- read.csv(text=r"(
ID, Properties
1,"{'gender': 'Male', 'nationality': 'IRL', 'document_type': 'passport', 'date_of_expiry': '2019-08-12', 'issuing_country': 'IRL'}"
2,"{'document_type': 'national_identity_card', 'date_of_expiry': '2027-01-23', 'issuing_country': 'CYP'}"
3,"{'date_of_expiry': '2019-01-28', 'issuing_country': 'JEY'}"
4,"{'document_type': 'driving_licence', 'date_of_expiry': '2006-06-14', 'issuing_country': 'POL'})")

# 核心处理逻辑
output <- input %>%
  # 将单引号替换为标准JSON要求的双引号
  mutate(Properties = str_replace_all(Properties, "'", '"')) %>%
  # 逐行解析JSON,转换为单行数据框格式,缺失字段自动留空
  mutate(parsed = map(Properties, ~ fromJSON(.x) %>% as_tibble_row())) %>%
  # 展开解析后的字段,和原有ID列合并
  unnest(parsed) %>%
  # 可选:删除原始的类JSON列,不需要可以删掉这行
  select(-Properties)

适配实际数据说明

把代码中的input替换为你导入到R中的Excel数据框,Properties替换为你实际存储类JSON字符串的列名即可直接使用。


内容的提问来源于stack exchange,提问作者sthurman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 13:39:04