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

1.6k views Asked by At

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

There are 1 answers

1
karthik manchala On BEST ANSWER

You can use the following:

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

See DEMO