2017-08-05 65 views
0

我對API中的json數據有很多觀察,我試圖將「FIPS」變成數據框。不是每個拉都是成功的,留下空值和不規則的格式。當我嘗試只是拉頭,使用不規則格式處理JSON數據?

library(rjson) 
    test<-"{\"status\":\"OK\",\"responseTime\":9,\"message\":[],\"Results\":{\"block\":[{\"envelope\":{\"maxy\":11.11111111,\"minx\":-11.11111111,\"maxx\":-11.1111111111,\"miny\":11.01111111111},\"geographyType\":\"BLOCK2010\",\"FIPS\":\"11111111111\"}]}}" 
    test1<-fromJSON(test) 
    names(test1) 

    test1$Results$block$FIPS 
    test.block.df<-as.data.frame(test1$Results$block$FIPS) 

在重複的例子:

rep<-c("{\"status\":\"OK\",\"responseTime\":10,\"message\":[\"No Block results found\"],\"Results\":{\"block\":[]}}", "{\"status\":\"OK\",\"responseTime\":9,\"message\":[],\"Results\":{\"block\":[{\"envelope\":{\"maxy\":00.0000000000,\"minx\":-00.000000000,\"maxx\":-00.00000000,\"miny\":00.0000000000000},\"geographyType\":\"BLOCK2010\",\"FIPS\":\"111111111121\"}]}}" ) 
rep1<-fromJSON(rep) 
names(rep1) 
rep1$result$block 

但在此之後,我無法分析到這之後FIPS。先謝謝你。

+0

它看起來在這種情況下數據likee具有兩個響應其是有時使用JSON「記錄」格式。線索是序列'} {'檢查兩個結構是否實際上被新行分隔,並嘗試'readLines'來分別獲取每行並將'fromJSON'應用於每行。 – epi99

回答

0

有兩個問題:1)00.0000的數字格式不由jsonlite處理。 2)每個請求可以返回多個響應,每一個格式化爲一個獨立的JSON結構

library(jsonlite) 
rep<-c("{\"status\":\"OK\",\"responseTime\":10,\"message\":[\"No Block results found\"],\"Results\":{\"block\":[]}}", "{\"status\":\"OK\",\"responseTime\":9,\"message\":[],\"Results\":{\"block\":[{\"envelope\":{\"maxy\":00.0000000000,\"minx\":-00.000000000,\"maxx\":-00.00000000,\"miny\":00.0000000000000},\"geographyType\":\"BLOCK2010\",\"FIPS\":\"111111111121\"}]}}" ) 

## jsonlite seems to choke on the number format 00.0000, 
rep_fixed <- gsub("\\:\\-?00\\.", "\\:0.", rep) 

# multiple results are returned each time, to apply to each structure 
rep1 <- lapply(rep_fixed, fromJSON) 
str(rep1) 

rep1[[2]][['Results']][['block']] 

# envelope.maxy envelope.minx envelope.maxx envelope.miny geographyType   FIPS 
#    0    0    0    0  BLOCK2010 111111111121 
+0

非常感謝。我改變了數字格式,因爲這些是個人地址的座標,我改變它的格式是令人遺憾的。這個答案是非常有幫助的。 – prospectjoe