regex - 使用 str replace 删除 json 文档中的部分字符串用于许多记录

标签 regex r string-matching stringr

我想替换此文件中导致无效 json 参数的字符串。我可以手动删除第一个字符串 "_id": ObjectId( "539163d7bd350003"),并且可以将此 json 转换为数据框。有没有办法可以用str_replace之类的函数替换json文件的所有实例。我尝试了以下但无法使其工作。有什么建议?

library(RJSONIO)
library(stringr)

json_file<- '{ "_id" : ObjectId( "539163d7bd350003" ), "login" :    "vui", "id" : 369607, "avatar_url" : "https://avatars.mashupsusercontent.com/u/369607?", "gravatar_id" : "df8897ffebe16c5b0cd690925c63e190", "url" : "https://api.mashups.com/users/vui", "html_url" : "https://mashups.com/vui", "followers_url" : "https://api.mashups.com/users/vui/followers", "following_url" : "https://api.mashups.com/users/vui/following{/other_user}", "gists_url" : "https://api.mashups.com/users/vui/gists{/gist_id}", "starred_url" : "https://api.mashups.com/users/vui/starred{/owner}{/repo}", "subscriptions_url" : "https://api.mashups.com/users/vui/subscriptions", "organizations_url" : "https://api.mashups.com/users/vui/orgs", "repos_url" : "https://api.mashups.com/users/vui/repos", "events_url" : "https://api.mashups.com/users/vui/events{/privacy}", "received_events_url" : "https://api.mashups.com/users/vui/received_events", "type" : "User", "site_admin" : false, "org" : "amurath" }'

str_replace(json_file,"_id*" , "")
json_file <- fromJSON(json_file)


json_file <- lapply(json_file, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
 })

df<- do.call("rbind", json_file)
df<- data.frame(json_file)

最佳答案

您可以使用以下内容:

str_replace(json_file,"\"_id[^,]*,\\s*" , "")

DEMO

关于regex - 使用 str replace 删除 json 文档中的部分字符串用于许多记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30789823/

相关文章:

regex - 在 gtksourceview 中匹配整个字符串

r - 如何知道数据是R中的列表还是data.frame

algorithm - 归一化编辑距离

javascript - 使用 javascript 正则表达式从字符串中删除不需要的字符以输入 MYSQL 语句

r - 在字符串 : R 中搜索特殊模式

正则表达式查找包含空格和标点符号的精确匹配

python - 如何在 Jupyter 笔记本中使用 rpy2 绘制(内联)?

r - 在外部程序中打开由 R 创建的文件

javascript - 无法理解 javascript String.match(regexp) 方法的行为

php - 如何从 PHP 中的文本字符串中删除隐藏字符?