Harold
Harold

Reputation: 383

How to deal with json with single quote in datatable in R

I have a datatable with JSON. And I use jsonlite to deal with it.

library(data.table)
library(jsonlite)
a <- data.table(keyword = list("{'id': 2316, 'name': 'women's sexual identity'}"))

In order to use fromJSON, I need to convert ' to ".

a[, keywords2 := gsub("'", "\"", keyword)]
a[, fromJSON(keywords2, use.names = TRUE, fill = TRUE)]

But since there are ' in the name, like 'women's sexual identity'. After transformation, the record becomes this {"id": 2316, "name": "women"s sexual identity"}. It would generate error:

> a[, rbindlist(lapply(keywords2, fromJSON), use.names = TRUE, fill = TRUE)]
Error: lexical error: invalid char in json text.
           {"id": 2316, "name": "women"s sexual identity"}
                     (right here) ------^

Upvotes: 1

Views: 977

Answers (1)

akrun
akrun

Reputation: 887531

We can try with

a[, keywords2 := gsub("'(?![a-z])|(?<=\\{|\\s)'", '"', keyword, perl = TRUE)]

cat(a$keywords2, '\n')
#{"id": 2316, "name": "women's sexual identity"} 


a[, prettify(toJSON(keywords2))]
#[
# "{\"id\": 2316, \"name\": \"women's sexual identity\"}"
#]

Upvotes: 2

Related Questions