Remove part of the string in json document using str replace for many records

只愿长相守 提交于 2019-12-23 12:16:39

问题


I would like to replace a string in this file which is causing the invalid json arguments. I can manually delete the first string "_id" : ObjectId( "539163d7bd350003" ), and can convert this json to a data frame. Is there a way I can replace all the instances of json file with function like str_replace. I tried the following but couldn't make it work. Any suggestions?

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)

回答1:


You can use the following:

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

See DEMO



来源:https://stackoverflow.com/questions/30789823/remove-part-of-the-string-in-json-document-using-str-replace-for-many-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!