Skip to content
Prev 312607 / 398506 Next

reading json tables

Hi Michael

  The problem is that the content of the .js file is not JSON,
but actual JavaScript code.

You could use something like the following

tt = readLines("http://mbostock.github.com/protovis/ex/wheat.js")

txt = c("[", gsub(";", ",", gsub("var [a-zA-Z]+ = ", "", tt)), "]")
tmp = paste(txt, collapse = "\n")
tmp = gsub("([a-zA-Z]+):", '"\\1":', tmp)
o = fromJSON(tmp)
data = structure(o[1:2], names = c("wheat", "monarch"))

Basically, this
    removes the 'var <variable name> =' part
    replaces the ; with a , to separate elements
    quotes the names of the fields, e.g. year, wheat, wages
    puts the two global data objects into a top-level array ([]) container

This isn't ideal (as the regular expressions are not sufficiently specific
and could modify the actual values incorrectly). However, it does the job
for this particular file.
On 12/1/12 12:47 PM, Michael Friendly wrote: