Getting error lexical error: invalid char in json text

430 Views Asked by At

I am getting the error lexical error while running the following codes

library(highcharter)
library(shiny)


ui <- fluidPage(
  highchartOutput("map")
)

server <- function(input, output) {

  
  output$map <- renderHighchart({
    hcmap(
      "https://code.highcharts.com/mapdata/custom/world-lowres.js")  # Replace "custom/world" with your map name
  })
}

shinyApp(ui, server)

I need some help on resolving it.

1

There are 1 best solutions below

4
r2evans On

If you inspect mapdata before fromJSON (such as with str(mapdata)), you can see that it starts with something non-json:

### from the previous version of your question
mapdata <- readLines("https://code.highcharts.com/mapdata/custom/world-lowres.js", warn = FALSE, encoding = "UTF-8")
mapdata[1] <- gsub(".* = ", "", mapdata[1])
mapdata <- paste(mapdata, collapse = "\n")
mapdata <- stringr::str_remove(mapdata, ";$")

### divergence/exploration
str(mapdata)
#  chr "Highcharts.maps[\"custom/world-lowres\"]={\"title\":\"World, Miller projection, low resolution\",\"version\":\""| __truncated__

We need to remove everything up to and including that first = (at character 39).

obj <- jsonlite::fromJSON(sub("^[^=]*=", "", mapdata))
str(obj, max.level = 1)
# List of 9
#  $ title         : chr "World, Miller projection, low resolution"
#  $ version       : chr "2.1.0"
#  $ type          : chr "FeatureCollection"
#  $ copyright     : chr "Copyright (c) 2023 Highsoft AS, Based on data from Natural Earth"
#  $ copyrightShort: chr "Natural Earth"
#  $ copyrightUrl  : chr "http://www.naturalearthdata.com"
#  $ crs           :List of 2
#  $ hc-transform  :List of 1
#  $ features      :'data.frame':   213 obs. of  4 variables:

More comments on your original (since-changed) question code:

See that your gsub is not doing anything:

mapdata <- readLines("https://code.highcharts.com/mapdata/custom/world-lowres.js", warn = FALSE, encoding = "UTF-8")
str(mapdata)
#  chr "Highcharts.maps[\"custom/world-lowres\"]={\"title\":\"World, Miller projection, low resolution\",\"version\":\""| __truncated__
nchar(mapdata)
# [1] 170260
mapdata[1] <- gsub(".* = ", "", mapdata[1])
nchar(mapdata)
# [1] 170260

So your initial gsub is doing nothing because of the spaces you have around = that are not in the data. You could remove the spaces and see if that works.

Bottom line, though, is that whatever you are doing here needs to be done also before you call hcmap.