require(RJSONIO)
somedata1<-list(a=1,b='w')
fromJSON(toJSON(somedata1))
# $a
# [1] 1
# $b
# [1] "w"
somedata2<-list(a=1,b=2)
fromJSON(toJSON(somedata2))
# a b
# 1 2
somedata3<-list(a='v',b='w')
fromJSON(toJSON(somedata3))
# a b
# "v" "w"
fromJSON(toJSON(somedata3),simplify=StrictNumeric)
# $a
# [1] "v"
# $b
# [1] "w"
fromJSON(toJSON(somedata2),simplify=FALSE)
# $a
# [1] 1
# $b
# [1] 2
fromJSON(toJSON(somedata3),simplifyWithNames = FALSE)
# $a
# [1] "v"
# $b
# [1] "w"
fromJSON(toJSON(somedata2),simplifyWithNames = FALSE)
# $a
# [1] 1
# $b
# [1] 2
默认情况下,从上面的示例中,RJSON 将“同质标量元素的集合/数组简化为 R 向量”。可以使用simplify
或来控制这种简化simplifyWithNames
。在您的示例中,您可以执行以下任何操作来访问所需的元素:
require(RJSONIO)
resultsURL='http://ergast.com/api/f1/2012/1/results.json'
results.data.json=fromJSON(resultsURL)
results.data.json$MRData$RaceTable$Races[[1]]$Results[[8]]$Driver['familyName']
# familyName
# "Pérez"
results.data.json=fromJSON(resultsURL,simplify=FALSE)
results.data.json$MRData$RaceTable$Races[[1]]$Results[[8]]$Driver$familyName
# [1] "Pérez"
results.data.json=fromJSON(resultsURL,simplify=StrictNumeric)
results.data.json$MRData$RaceTable$Races[[1]]$Results[[8]]$Driver$familyName
# [1] "Pérez"
results.data.json=fromJSON(resultsURL,simplifyWithNames = FALSE)
results.data.json$MRData$RaceTable$Races[[1]]$Results[[8]]$Driver$familyName
# [1] "Pérez"