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

如何在R中拆分类JSON响应列并设置对应字段为列名

拆分类JSON格式的问卷响应为多列数据

你的df数据框中Response列存储的是类JSON结构的字符串,要将其拆分为包含ID、gender、occupation、handed的多列格式,最稳妥的方式是用专业的JSON解析工具,避免手动拆分字符串的潜在问题,下面是完整解决方案:

推荐方案:使用jsonlite解析JSON字符串

jsonlite包能完美处理这类JSON格式数据,步骤如下:

  1. 安装并加载所需包(如果未安装过jsonlite):
# install.packages("jsonlite")
library(jsonlite)
library(dplyr)
  1. 处理数据:
# 原始数据
df <- structure(list(ID = 1:2, Response = c("\"gender\":\"Female\",\"occupation\":\"student\",\"handed\":\"Left\"", 
"\"gender\":\"Female\",\"occupation\":\"Reporter\",\"handed\":\"Right\""
)), class = "data.frame", row.names = c(NA, -2L))

# 补全JSON格式并解析,展开为多列
result_df <- df %>%
  # 给每个响应字符串补全首尾的{},转为标准JSON对象
  mutate(Response = lapply(Response, \(x) fromJSON(paste0("{", x, "}")))) %>%
  # 将嵌套的列表展开为独立列
  unnest_wider(Response)
  1. 查看结果:
print(result_df)
#   ID gender occupation handed
# 1  1 Female    student   Left
# 2  2 Female   Reporter  Right

这种方法的优势在于:能正确处理带特殊字符(比如逗号、引号)的字段值,完全适配JSON格式的规范,比手动拆分字符串可靠得多。


基于你原有代码的改进方案(不推荐,仅作参考)

如果想基于你已经写的字符串拆分逻辑继续完善,可以按以下步骤调整,但请注意这种方法仅适用于字段值无特殊字符的场景:

library(dplyr)
library(tidyr)

# 你的原始拆分步骤
df <- df %>%
  mutate(NUM = row_number())

dfdelimted <- str_split_fixed(df$Response, ',\"', 50) %>%
  as.data.frame() %>%
  mutate(NUM = row_number())

merged_df <- merge(df, dfdelimted, by = "NUM") %>%
  select(-NUM, -Response) # 移除不需要的辅助列

# 拆分键值对并整理为宽格式
final_df <- merged_df %>%
  pivot_longer(cols = starts_with("V"), names_to = "temp", values_to = "key_value") %>%
  filter(key_value != "") %>% # 过滤空内容
  separate(key_value, into = c("key", "value"), sep = ':\"') %>%
  # 移除键和值两端的引号
  mutate(
    key = gsub('^\"', '', key),
    value = gsub('\"$', '', value)
  ) %>%
  pivot_wider(names_from = "key", values_from = "value") %>%
  select(ID, gender, occupation, handed) # 调整列顺序

print(final_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:43:24