本文介绍了JSON:R中的Google Map距离矩阵数据“如何将JSON数据下载到R?”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Google Map API距离矩阵中获取数据到R,我正在试图将JSON数据转化为R.如何将JSON数据下载到R中,以便稍后解析?

I am trying to get the data from the Google Map API Distance Matrix to R. I am trying to get the JSON data into R. How to download JSON data into R, so I will be able parse later?

require(rjson)
url <- "https://maps.googleapis.com/maps/api/distancematrix/jsonunits=imperial&origins=19+East+34th+Street+NewYork+NY+10016&destinations=40.5177433,-74.2749576&mode=transit&language=fr-FR&key=API_KEY_HERE"
raw.data <- readLines(url, warn = "F")
rd <- fromJSON(raw.data)

出现此错误:

I am getting this error:

Error in fromJSON(raw.data) : unexpected character '<'

感谢您的帮助

Thank you for the help

推荐答案

恰好我写了一个包,,可以提供帮助:

It just so happens I've written a package, googleway that can help:

library(googleway)

google_distance(origins = "19 East 34th Street NewYork NY 10016",
                destinations = list(c(40.5177433,-74.2749576)),
                key = key,
                mode = "transit",
                language = "fr")

$destination_addresses
[1] "350-356 Lawrie St, Perth Amboy, NJ 08861, États-Unis"

$origin_addresses
[1] "19 E 34th St, New York, NY 10016, États-Unis"

$rows
elements
1 51,3 km, 51305, 1 heure 27 min, 5249, OK

$status
[1] "OK"

类似地,设置 simplify = FALSE 来获取原始json

Similarly, set simplify = FALSE to get the raw json

google_distance(origins = "19 East 34th Street NewYork NY 10016",
                destinations = list(c(40.5177433,-74.2749576)),
                key = key,
                mode = "transit",
                language = "fr",
                simplify = FALSE)


[1] "{"
[2] "   \"destination_addresses\" : [ \"350-356 Lawrie St, Perth Amboy, NJ 08861, États-Unis\" ],"
[3] "   \"origin_addresses\" : [ \"19 E 34th St, New York, NY 10016, États-Unis\" ],"
[4] "   \"rows\" : ["
[5] "      {"
[6] "         \"elements\" : ["
[7] "            {"
[8] "               \"distance\" : {"
[9] "                  \"text\" : \"51,3 km\","
[10] "                  \"value\" : 51305"
[11] "               },"
[12] "               \"duration\" : {"
[13] "                  \"text\" : \"1 heure 27 min\","
[14] "                  \"value\" : 5249"
[15] "               },"
[16] "               \"status\" : \"OK\""
[17] "            }"
[18] "         ]"
[19] "      }"
[20] "   ],"
[21] "   \"status\" : \"OK\""
[22] "}"

(其中 simplify == TRUE 使用 jsonlite :: fromJSON

这篇关于JSON:R中的Google Map距离矩阵数据“如何将JSON数据下载到R?”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:55