【问题标题】:Remove part of the string in json document using str replace for many records对许多记录使用 str 替换删除 json 文档中的部分字符串
【发布时间】:2015-08-27 16:21:45
【问题描述】:

我想替换此文件中导致无效 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)

【问题讨论】:

  • @akrun 不需要str_replace_all.. 因为id 是每个文档一次(mongodb)
  • @karthikmanchala 这只是一个猜测,因为 OP 的代码适用于给定的示例
  • 问题出在字符串本身。我可以用你提到的函数替换像“login”这样的词,但我想用“”替换这种类型的字符串“”_id”:ObjectId(“539163d7bd350003”),“我有对象id中的数字不断变化有记录!
  • 是的,它工作得很好!我需要检查多条记录!
  • @karthikmanchala 我收到了这个错误!错误:'\s' 是从 ""\"_id[^,]*,\s" 开始的字符串中无法识别的转义

标签: regex r string-matching stringr


【解决方案1】:

您可以使用以下内容:

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

DEMO

【讨论】:

  • 我正在尝试 [link] (regex101.com/r/vA6mZ3/15) 解决另一个问题。我不能直接在 R str_replace 中使用它。你能建议 str_replace_all(json_file, "\",{author[^*]*],\\s*","") 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 2022-01-09
  • 2015-03-31
相关资源
最近更新 更多