Aziz Ilyosov
Aziz Ilyosov

Reputation: 57

Converting JSON data into data.frame

How can I convert this kind of JSON data to data.frame:

library("rjson")
fromJSON("[{'id': 18, 'name': 'Drama'}, {'id': 28, 'name': 'Action'}, {'id': 10749, 'name': 'Romance'}]")

Error in fromJSON("[{'id': 18, 'name': 'Drama'}, {'id': 28, 'name': 'Action'}, {'id': 10749, 'name': 'Romance'}]") : unexpected character "'"; expecting opening string quote (") for key value when I used fromJSON() I got this:unexpected character "'"; expecting opening string quote (") for key value

Upvotes: 2

Views: 1214

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26248

For JSON to be valid it needs double-quotes inside the JSON string (see this question for reference). Therefore, you also need single-quotes surrounding it to make it a valid string in R.

You can swap your single and double quotes by using that awesome piece of regex supplied by r2evans

## this is your invalid string
js <- "[{'id': 18, 'name': 'Drama'}, {'id': 28, 'name': 'Action'}, {'id': 10749, 'name': 'Romance'}]"

## convert it to a valid string
js <- gsub("QUUX", "'", gsub("'", '"', gsub('"', "QUUX", js)))

Or by making use of the ?chartr function (thanks to thelatemail)

js <- chartr("\'\"","\"\'",js)

Then most JSON parsing libraries should work, for example,

Using jsonlite will give you a data.frame

df <- jsonlite::fromJSON(js)

df
#     id    name
#1    18   Drama
#2    28  Action
#3 10749 Romance

And using rjson will give you a list

rjson::fromJSON(js)

[[1]]
[[1]]$id
[1] 18

[[1]]$name
[1] "Drama"


[[2]]
[[2]]$id
[1] 28

[[2]]$name
[1] "Action"


[[3]]
[[3]]$id
[1] 10749

[[3]]$name
[1] "Romance"

Upvotes: 3

Related Questions