简体   繁体   中英

Replace empty brackets in a json file using r

I have a large json file that I want to convert to a data frame with R thas some empty lines which look like this:

{}

After conversion these lines are gone thats why I want to put something in.

Can somebody help?

I tried using gsub like this (see below).

Unfortunately this doesn't work and all other lines that have some content are messed up afterwards.

Before {}

Code:

d <- gsub('[{}]', '{\"gender\": \"NA\", \"nationality\": \"NA\", \"document_type\": \"passport\", \"date_of_expiry\": \"2019-08-12\", \"issuing_country\": \"NA\"}' , d)

so after conversion I want all empty line {} to look like this:

{\"gender\": \"NA\", \"nationality\": \"NA\", \"document_type\": \"passport\", \"date_of_expiry\": \"2019-08-12\", \"issuing_country\": \"NA\"}

all other lines that have content eg

{\"gender\": \"Male\", \"nationality\": \"IRL\", \"document_type\": \"passport\", \"date_of_expiry\": \"2019-08-12\", \"issuing_country\": \"IRL\"}

I want to stay the same.

This might be because brackets are used as special characters in regex rules (see this cheatsheet ). Try escaping them, so something like pattern = '\\\\{\\\\}' .

If that doesn't work you could try using a different operator to simply identify where the occurrences are happening before removing them -- this might help you see what is going wrong and debug the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM