2

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

Aziz Ilyosov
  • 57
  • 1
  • 11
  • 3
    look into the package called `jsonlite` – zacdav Nov 20 '17 at 02:45
  • 3
    Possible duplicate of [Parse JSON with R](https://stackoverflow.com/questions/2061897/parse-json-with-r) – Kevin Arseneau Nov 20 '17 at 02:52
  • 3
    a `vector` is probably not what you want for this data, you probably want a `data.frame`. Also, you'll need to replace the single-quotes with doubles, and the double-quotes with singles ([reference](https://stackoverflow.com/q/14355655/5977215) ) – SymbolixAU Nov 20 '17 at 02:55
  • this is last error what I got: 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 – Aziz Ilyosov Nov 20 '17 at 03:27

1 Answers1

3

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"
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139