Home > Enterprise >  Reading JSON file using R
Reading JSON file using R

Time:07-30

product_id.datahandler({"ID": [], "ProductName": ["Marbel Mabel"], "Description": ["pearl white, natural marbel"] .....})

I have a data as above. I tried to read it as JSON using fromJSON but failed (not all data was parsed (0 chars were parsed out of a total of 39890 chars)). How could i clean product_id.datahandler( and ) first before using fromJSON to read as JSON file?

CodePudding user response:

You could maybe use some regex to clean the string? Here using stringr:

library(stringr)
library(jsonlite)

jsontext <- 'product_id.datahandler({"ID": [], "ProductName": ["Marbel Mabel"], "Description": ["pearl white, natural marbel"]})'

jsontext |>
  jsonlite::fromJSON()

#Error: lexical error: invalid char in json text.
#product_id.datahandler({"ID": [
#  (right here) ------^

jsontext |>
  str_replace_all(".*\\..*\\(\\{", "\\{") |> # Matching: "character.character({"
  str_replace_all("\\}\\)", "\\}") |> 
  jsonlite::fromJSON()

#$ID
#list()
#
#$ProductName
#[1] "Marbel Mabel"
#
#$Description
#[1] "pearl white, natural marbel"
  • Related