从R读取JSON文件

时间:2010-08-06 07:50:49

标签: json r

我尝试使用JSON从R中读取rjson文件,但不断收到错误。我使用各种在线验证器验证了JSON文件。以下是JSON文件的内容:

{
   "scenarios": [
      {
         "files": {
            "type1": "/home/blah/Desktop/temp/scen_0.type1",
            "type2": "/home/blah/Desktop/temp/scen_0.type2"
         },
         "ID": "scen_0",
         "arr": [],
         "TypeToElementStatsFilename": {
            "type1": "/home/blah/Desktop/temp/scen_0.type1.elements",
            "type2": "/home/blah/Desktop/temp/scen_0.type2.elements"
         }
      }
   ],
   "randomSeed": "39327314969888",
   "zone": {
      "length": 1000000,
      "start": 1
   },
   "instanceFilename": "/home/blah/bloo/data/XY112.zip",
   "txtFilename": "/home/blah/bloo/data/XY112.txt",
   "nSimulations": 2,
   "TypeTodbFilename": {
      "type1": "/home/blah/bloo/data/map.type1.oneAmb.XY112.out"
   },
   "arr": {
      "seg11": {
         "length": 1000,
         "start": 147000
      },
      "seg12": {
         "length": 1000,
         "start": 153000
      },
      "seg5": {
         "length": 1000,
         "start": 145000
      },
      "seg6": {
         "length": 1000,
         "start": 146000
      },
      "seg1": {
         "length": 100,
         "start": 20000
      }
   },
   "outPath": "/home/blah/Desktop/temp",
   "instanceID": "XY112",
   "arrIds": [
      "seg5",
      "seg6",
      "seg1",
      "seg11",
      "seg12"
   ],
   "truth": {
      "files": {
         "type1": "/home/blah/Desktop/temp/truth.type1",
         "type2": "/home/blah/Desktop/temp/truth.type2"
      },
      "ID": "truth",
      "TypeToElementStatsFilename": {
         "type1": "/home/blah/Desktop/temp/truth.type1.elements",
         "type2": "/home/blah/Desktop/temp/truth.type2.elements"
      }
   }
}

错误:

> json_file <- "~/json"
> json_data <- fromJSON(paste(readLines(json_file), collapse=""))
Error in fromJSON(paste(readLines(json_file), collapse = "")) :
  unexpected character: :

3 个答案:

答案 0 :(得分:6)

RJSON对空数组感到不满。

  

fromJSON('{“arr”:[]}')

fromJSON中出错(“{\”arr \“:[]}”):意外字符:

答案 1 :(得分:2)

您可以在RJSONIO托管的http://www.omegahat.org包中尝试使用fromJSON功能。它似乎读得很好。

答案 2 :(得分:0)

有一个解决方法。

创建一个新函数来替换RCurl中使用的现有getURL函数,你应该有你的解决方案。

myGetURL <- function(...) {
    rcurlEnv <- getNamespace("RCurl")
    mapUnicodeEscapes <- get("mapUnicodeEscapes", rcurlEnv)
    unlockBinding("mapUnicodeEscapes", rcurlEnv)
    assign("mapUnicodeEscapes", function(str) str, rcurlEnv)
    on.exit({
        assign("mapUnicodeEscapes", mapUnicodeEscapes, rcurlEnv)
        lockBinding("mapUnicodeEscapes", rcurlEnv)
    }, add = TRUE)
    return(getURL(...))
}

测试:

> json <- myGetURL("http://abicky.net/hatena/rcurl/a.json")
> cat(json, fill = TRUE)
{"a":"\\\"\u0030\\\""}
> fromJSON(json)
$a
[1] "\\\"0\\\""