How do I write a json array from R that has a sequence of lat and long?
如何从R编写一个具有lat和long序列的json数组?
I would like to write:
我想写:
[[[1,2],[3,4],[5,6]]]
the best I can do is:
我能做的最好的事情是:
toJSON(matrix(1:6, ncol = 2, byrow = T))
#"[ [ 1, 2 ],\n[ 3, 4 ],\n[ 5, 6 ] ]"
How can I wrap the thing in another array (the json kind)? This is important to me so I can write files into a geojson format as a LineString.
如何将该东西包装在另一个数组(json类)中?这对我很重要,因此我可以将文件作为LineString写入geojson格式。
2 个解决方案
#1
5
I usually use fromJSON
to get the target object :
我通常使用fromJSON来获取目标对象:
ll <- fromJSON('[[[1,2],[3,4],[5,6]]]')
str(ll)
List of 1
$ :List of 3
..$ : num [1:2] 1 2
..$ : num [1:2] 3 4
..$ : num [1:2] 5 6
So we should create , a list of unnamed list, each containing 2 elements:
所以我们应该创建一个未命名的列表列表,每个列表包含2个元素:
xx <- list(setNames(split(1:6,rep(1:3,each=2)),NULL))
identical(toJSON(xx),'[[[1,2],[3,4],[5,6]]]')
[1] TRUE
#2
0
If you have a matrix
如果你有一个矩阵
m1 <- matrix(1:6, ncol=2, byrow=T)
may be this helps:
可能有帮助:
library(rjson)
paste0("[",toJSON(setNames(split(m1, row(m1)),NULL)),"]")
#[1] "[[[1,2],[3,4],[5,6]]]"
#1
5
I usually use fromJSON
to get the target object :
我通常使用fromJSON来获取目标对象:
ll <- fromJSON('[[[1,2],[3,4],[5,6]]]')
str(ll)
List of 1
$ :List of 3
..$ : num [1:2] 1 2
..$ : num [1:2] 3 4
..$ : num [1:2] 5 6
So we should create , a list of unnamed list, each containing 2 elements:
所以我们应该创建一个未命名的列表列表,每个列表包含2个元素:
xx <- list(setNames(split(1:6,rep(1:3,each=2)),NULL))
identical(toJSON(xx),'[[[1,2],[3,4],[5,6]]]')
[1] TRUE
#2
0
If you have a matrix
如果你有一个矩阵
m1 <- matrix(1:6, ncol=2, byrow=T)
may be this helps:
可能有帮助:
library(rjson)
paste0("[",toJSON(setNames(split(m1, row(m1)),NULL)),"]")
#[1] "[[[1,2],[3,4],[5,6]]]"